I have a Class like this:
public delegate void ChangedEventHandler(object sender, EventArgs e); [Serializable] public class valueDouble { public event ChangedEventHandler Changed; public double value { get { return _value; } set { _value = value; if (Changed != null) { Changed(this, EventArgs.Empty); } } } private double _value = 0; }
I also have another Class (StepPulseblaster) which is not serializable and adds an Event Handler
valDouble.Changed += new ChangedEventHandler(sc_PropertyChanged);
When i try to serialize the valueDouble Class, there will be an error:
The Type StepPulseblaster is not marked as serializable
When i comment the line
valDouble.Changed += ...
there will be no error any more.
How can i serialize a class which has some events connected?
To serialize an object means to convert its state to a byte stream so that the byte stream can be reverted back into a copy of the object. A Java object is serializable if its class or any of its superclasses implements either the java. io. Serializable interface or its subinterface, java.
There are three types of serialization in . Net : Binary Serialization, SOAP Serialization and XML Serialization.
Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.
Serializing is about moving structured data over a storage/transmission medium in a way that the structure can be maintained. Encoding is more broad, like about how said data is converted to different forms, etc.
You should do:
[field: NonSerialized] public event ChangedEventHandler Changed;
As described in the MSDN:
To apply the NonSerializedAttribute class to an event, set the attribute location to field.
The NonSerialized attribute is only available for fields, so to use it you have to adjust your code to use fields.
Try creating your event like this:
[NonSerialized] private ChangedEventHandler _changed; public event ChangedEventHandler Changed { add { _changed += value; } remove { _changed -= value; } }
Then in the value property use the field, not the property:
public double value { get { return _value; } set { _value = value; if (_changed != null) { _changed(this, EventArgs.Empty); } } } private double _value = 0;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With