Next, the content in the previous section, sometimes we need to serialize not all fields in the object.
Example:
The following lists the entity classes required for this form.
Using System;
Using System. Collections. Generic;
Using System. text;
Using System. runtime. serialization;
Using System. collections;
Namespace Mutliobjectserialization2
{
[Serializable]
Class Collegestudent: ideserializationcallback
{
Public String name = " Null " ; // Name
Public Bool Ismale = True ; // Gender
Public Int Scoreforentranceexamination = 0 ; // Entrance Exam Score
Public Datetime Birthday = datetime. now; // Birthday
[Nonserialized]
Public Int Age = 0 ; // Age
Void Ideserializationcallback. ondeserialization (Object sender)
{
Age = datetime. Now. Year-BirthDay.Year;
}
}
[Serializable]
Class Studentlist // Student list
{
Public List <collegestudent> students = New List <collegestudent> ();// Student object set
}
}
If we think about it, we will find that the "Age" field is very special. It depends on the value of the "Birthday" field and will change over time. If this field is also serialized to the file during serialization, the value of the "Age" field will remain unchanged no matter when the object is rebuilt. This is obviously not in line with the actual situation.
In fact, as long as you know your birthday and subtract the date of the time, you can know the person's age. Therefore, you can choose not to serialize the "Age" field, during deserialization, the field age is calculated and then entered. This requires some adjustments to the default Object serialization process of. NET Framework.
In. NET Framework, add the [nonserialized] Mark to a field of the class so that this field does not participate in serialization.
. NET Framework also provides an ideserializationcallback interface, which defines an ondeserialization method that can be automatically called when deserialization is complete.In other words, if the collegestudent class implements the ideserializationcallback interface (providing an ondeserialization method), the CLR automatically calls the defined ondeserialization method when the collegestudent object is rebuilt from the stream, you can write in this methodCodeCalculate the age and fill in the "Age" field.
This topic describes how to use the [nonserialized] Mark and ideserializationcallback interfaces to control the serialization process. In addition, the framework provides the following four code tags for more control measures.
[Onserializedattribute]: called after serialization.
[Onserializingattribute]: called during serialization.
[Ondeserializedattri]: called after deserialization.
[Ondeserializingattribute]: called during deserialization.
If you attach these tags to a method (only one tag can be attached to a method), these methods are automatically called at the right time.