In my previous article ". Net brief introduction to component programming (serialization and persistence at first glance)", we basically learned what serialization and persistence are. Through the services provided by the system, we can easily serialize binary and soap protocols.
This article explains how to use advanced functions to control serialization and deserialization. [Wang qingpei has all rights reserved. For more information, please sign it.]
Here is an additional remark: in fact, there are a lot of things to learn from when we write our own components. NET platform has some advantages, and its functions are not dead. You can subscribe to and cut in. When writing components, we should also consider some advanced features.
The above section is actually used to pave the way. It means that when the serialization component is working, we can "join" it.
During work, the iformatter formatter interface checks whether the object to be serialized is marked with the serializable feature. If so, it performs deep recursive traversal or wide recursive traversal of all members, if an internal Member is marked with a nonserialized disable serialization feature, iformatter skips the member. If the serialization is not disabled for all members inside the object, it will go through the serialization project. Therefore, it is difficult to ensure that the serialization can be successfully recursively traversed on a special object.
A typical object is the event object. In the subscription list, we cannot ensure that all subscribers can be serialized, but we want to initialize some data during deserialization.
Ideserializationcallback Interface
Using system; using system. runtime. interopservices; namespace system. runtime. serialization {// Abstract: // indicates the notification class when deserializing the entire object image. [Comvisible (true)] public interface ideserializationcallback {// Summary: // run when the entire object image has been deserialized. //// Parameter: // Sender: // the object that starts the callback. This parameter is not currently available. Void ondeserialization (Object sender );}}
The ideserializationcallback interface is the interface that will be executed during deserialization. There is only one ondeserialization method in the interface. During deserialization, the system checks whether the object to be serialized has implemented the ideserializationcallback interface. If yes, then the system calls the ondeserialization method in this interface.
[Wang qingpei has all rights reserved. For more information, please sign it.]
So how can we use this method? Let's look at the Code;
Using system; using system. collections. generic; using system. text; using system. runtime. serialization; namespace consoleapplication1. serialization and persistence {[serializable] public class myclass: ideserializationcallback {public myclass () {} Public String number = "myclass status"; [field: nonserialized] // The event must be decorated with the field public event eventhandler event; # region ideserializationcallback member public void ondeserialization (Object sender) {}# endregion )}}
The myclass class has an event object. We have added the serialization prohibition feature on it. The previous field is used to treat the event object as a field, nonserialized can only be used in field fields.
We implement the ideserializationcallback interface. The method of this interface will be executed each time during deserialization.
Using system; using system. collections. generic; using system. text; using system. runtime. serialization; using system. runtime. serialization. formatters. binary; using system. runtime. serialization. formatters. soap; using system. runtime. serialization. formatters; using system. io; namespace consoleapplication1. serialization and persistence {public static class program {public static void main () {soapformatter formatter = new soapformatter (); stream = new filestream ("obj. XML ", filemode. create, fileaccess. write); Using (Stream) {myclass = new myclass (); myclass. event + = new eventhandler (myclass_event); formatter. serialize (stream, myclass);} stream stream1 = new filestream ("obj. XML ", filemode. open, fileaccess. read); Using (stream1) {myclass = formatter. deserialize (stream1) as myclass;} static void myclass_event (Object sender, eventargs e ){}}}
We subscribe to Event Events in the myclass class. If I have not added the disable serialization feature to Event Events in the myclass class, an error is returned when serialization is executed.
If the object myclass needs to exist again, an event subscriber is required, such as the log record and message sending in the object. We can process it in the ondeserialization method.
Using system; using system. collections. generic; using system. text; using system. runtime. serialization; namespace consoleapplication1. serialization and persistence {[serializable] public class myclass: ideserializationcallback, iserializable {public myclass () {} Public String number = "myclass status"; [field: nonserialized] // The event must be decorated with the field public event eventhandler event; # region ideserializationcallback member public void ondeserialization (Object sender) {}# endregion )}}
Serialize lifecycle events
In the process of serialization and deserialization, the system will go through several processes. It can be roughly divided into the following four types,
Before serialization (onserializing), after serialization (onserialized), before deserialization (ondeserializing), after deserialization (ondeserialized), and then the system leaves the entry for us, we can perform some process control by participating in these methods. See the code;
[OnSerializing] void OnSerializing(StreamingContext context) { } [OnSerialized] void OnSerialized(StreamingContext context) { } [OnDeserializing] void OnDeSerializing(StreamingContext context) { } [OnDeserialized] void OnDeserizlized(StreamingContext context) { }
These features are used to mark the process of serialization components. The system will call these methods separately during processing. We can control the process in several methods. Streamingcontext is the object of the serialized stream. We can obtain the target of the serialized stream.
Iserializable Interface
Using system; using system. runtime. interopservices; namespace system. runtime. serialization {// Abstract: // allows an object to control its own serialization and deserialization processes. [Comvisible (true)] public interface iserializable {// Summary: // fill in system. runtime. serialization. serializationinfo with the data required to serialize the target object. //// Parameter: // info: // system. runtime. serialization. serializationinfo. /// Context: // the serialization target (see system. runtime. serialization. streamingcontext ). //// Exception: // system. Security. securityexception: // The caller does not have the required permissions. Void getobjectdata (serializationinfo info, streamingcontext context );}}
If we want to further control the serialization and deserialization processes, we will implement the iserializable interface, through which we can basically control all data in serialization and deserialization.
We add the code in the myclass class.
Public void getobjectdata (serializationinfo info, streamingcontext context) {info. addvalue ("Number", "manually added status") ;}# endregion // deserialization constructor protected myclass (serializationinfo info, streamingcontext context) {This. number = (string) info. getvalue ("Number", typeof (string ));}
We implemented the iserializable interface, which contains only one method getobjectdata. This method is called by the system to obtain the serialized data pair. We set it through the serializationinfo object. In fact, serializationinfo is the packaging of the streamingcontext object, the main purpose is to set the data. Streamingcontext refers to the reference of the serialized stream, and finally writes the data into the stream.
One important thing is that the system does not call the default constructor of the object marked by the serializable feature during deserialization, because the system is not sure whether the constructor can restore all data of the object, because some nonserializable mark objects may be filtered during serialization. Therefore, the system will call a defined overload constructor, which is what I wrote above:
Protected myclass (serializationinfo info, streamingcontext context)
The system uses the serializationinfo and streamingcontext objects to restore the data originally serialized into streamcontext. [Wang qingpei has all rights reserved. For more information, please sign it.]