An existing object (objectA) needs to be serialized into a binary file using BinaryFormatter:
FileStream fileStream = new FileStream(path, FileMode.Create);BinaryFormatter formatter = new BinaryFormatter();formatter.Serialize(fileStream, objectA);
The object objectA is defined as follows:
[Serializable()] public class ObjectA { public string Name { set; get; } public event EventHandler<EventArgs> Created; }
Note: The object ObjectA has an event: Created.
If an object that cannot be serialized (such as WinForm) subscribes to the ObjectA Created event, an error occurs during serialization:
In this regard, I have not found a good explanation, even the official Microsoft documentation does not mention anything (or I do not understand it ).
http://msdn.microsoft.com/zh-cn/library/system.runtime.serialization.formatters.binary.binaryformatter(v=vs.100).aspx
Complete code:
Using System; using System. collections. generic; using System. componentModel; using System. data; using System. drawing; using System. linq; using System. text; using System. windows. forms; using System. runtime. serialization. formatters. binary; using System. IO; namespace BinarySerializer {public partial class Form1: Form {public Form1 () {InitializeComponent ();} private void button#click (object sender, EventArgs e) {Sa VeFileDialog dialog = new SaveFileDialog (); if (dialog. showDialog () = System. windows. forms. dialogResult. OK) {try {ObjectA objectA = new ObjectA {Name = "A"}; if (checkBox1.Checked) objectA. created + = new EventHandler <EventArgs> (objectA_Created); // when an object is serialized, if the object event is subscribed to by another object, a serialization failure error occurs, if this statement is deregistered, the serialization is successful. String path = dialog. fileName; FileStream fileStream = new FileStream (path, FileMode. create); BinaryFormatter formatter = new BinaryFormatter (); formatter. serialize (fileStream, objectA); MessageBox. show ("saved successfully");} catch (Exception ex) {MessageBox. show (ex. message) ;}} void objectA_Created (object sender, EventArgs e) {throw new NotImplementedException () ;}} [Serializable ()] public class ObjectA {public string Name {set; get;} public event EventHandler <EventArgs> Created ;}}
Demo:Demo of serialization failure of objects with events
Solution:
When the [field: NonSerialized] label is added to the event, the event will not be serialized.
http://www.baryudin.com/blog/events-and-binaryformatter-serialization-net.html
http://stackoverflow.com/questions/2308620/why-is-binaryformatter-trying-to-serialize-an-event-on-a-serializable-class