I recently implemented a Copy&Paste feature into an application I am working on. This works pretty much as intended.
I create a new item in my user interface and can copy and paste it as often as I want without any issues. But when I copy&paste an item that was produced by a previous copy&paste action, I get aSerializationException
. It complains about a certain type not being marked as serializable.
This is where the confusion starts. The first copy&paste action interacts with the same kind of objects as the second. But the second results in the exception.
To be a little more detailed, I have a class Slide
, this is the class that is the target of the copy&paste operation. So, I place an instance of that object in the clipboard and paste it again into the same container. This works out as intended开发者_开发知识库. Now I copy that inserted object and it try to paste it. This is when the exception is thrown. The exception complains about a class SlideEditorUi
. SlideEditorUi
is a UserControl
that interacts with a class called SlideEditor
. Which in turn interacts with a Slide
instance. But no Slide
instance has a reference back to any of the for-mentioned classes.
Usually the problem in this scenario is an event holding a reference to another object. BinaryFormatter
follows the underlying field back to the object and boom.
If you can find the offending event you can use (for a "field-like" event):
[field:NonSerialized]
public event SomeEventHandler EventName;
or for an explicit implementation, add [NonSerialized]
to the backing field.
Alternatively; use something other than BinaryFormatter
;p Json or xml make simple formats that you can use via a string, or for larger / more complex objects there are other binary serialization formats.
The error is about a part of your data object that isn't containing the SerializableAttribute
. Why it doesn't throw on serialization, but does on reserializing, I don't know. Perhaps it would be good to see the POCO that you're trying to serialize. What I suspect, is that you indeed miss that attribute on a property or field.
Note the following (from the documentation link above), esp. the "graph" word, which means, all classes, of parents, aggregates and references need to be serializable for the error not to throw:
Apply the SerializableAttribute attribute to a type to indicate that instances of this type can be serialized. The common language runtime throws SerializationException if any type in the graph of objects being serialized does not have the SerializableAttribute attribute applied.
精彩评论