Use SerializableAttribute for Object serialization and deserialization

Source: Internet
Author: User

The SerializableAttribute attribute is used to modify classes that can be serialized. If the class supports serialization, you can use this attribute to modify the class. Note that not all classes supporting serialization need to be modified by SerializableAttribute. Only when the class needs or may require serialization, such as some entity classes, may need to be persistent or used for inter-process transmission. Such objects need to be serialized into word throttling or other formats for storage or transmission, and can be restored or deserialized to memory through this persistent format. All classes modified using SerializableAttribute can be serialized by formatting classes such as System. Runtime. Serialization. Formatters. Binary. BinaryFormatter. For example, [csharp] [Serializable] public class Class1 {public string Name {get; set;} public string ID {get; set ;}} Class1 cls1 = new Class1 (); cls1.Name = "Class1"; cls1.ID = "cls-1"; BinaryFormatter formatter = new BinaryFormatter (); using (FileStream stream = new FileStream ("c: \ Class1.bin", FileMode. create, FileAccess. write) {formatter. serialize (stream, cls1);} using (FileStream stream = new FileStream ("c: \ Class1.bin", FileMode. open, FileAccess. read) {Class1 cls2 = formatter. deserialize (stream) as Class1;} But if Class1 is not modified by SerializableAttribute. serialize (stream, cls1) will throw the SerializationException "Type 'xxxx. class1 'in Assembly ..... is not marked as serializable. ", so to be serialized by formatting classes such as BinaryFormatter, you must use SerializableAttribute. Unless you want to write the serialization method yourself and serialize the object through reflection. In addition, you must note that all classes, structures, and enumeration can be modified using SerializableAttribute, but not all classes or structures are suitable for serialization, some fields cannot be serialized or deserialized. For example, the pointer (IntPtr type), because during the serialization, the pointer address will be persistent, but in the deserialization, the content pointed to by the pointer address will not be the original content. Unless the pointer does not need to be serialized, you can use NonSerializedAttribute to modify these fields that do not support serialization. In fact, SerializableAttribute is only an identifier used to indicate that classes can be serialized. But whether the actual class is really suitable for serialization requires the consideration of the class designer. The designer needs to determine whether the serializable field of the object contains an inappropriate type such as pointer. Because the class user only knows that the class is modified by SerializableAttribute, it is considered serializable, that's all.. Net framework also provides a serialization interface System. runtime. serialization. ISerializable. This interface is mainly used for custom serialization. The class that implements this interface must be modified by SerializableAttribute to be serialized by BinaryFormatter. The use of ISerializable can skip the modification of NonSerialized and run the process of controlling serialization and deserialization. Example: [csharp] [Serializable] public class Class1: ISerializable {public string Name {get; set;} public string ID {get; set;} [NonSerialized] private DateTime BirthDate; public void SetBirthDate (DateTime birthdate) {this. birthDate = birthdate;} public virtual void GetObjectData (SerializationInfo info, StreamingContext context) {info. addValue ("Name", this. name); info. addValue ("ID", this. ID ); Info. addValue ("BirthDate", this. birthDate);} public Class1 () {} protected Class1 (SerializationInfo, StreamingContext context) {this. name = info. getString ("Name"); this. ID = info. getString ("ID"); this. birthDate = info. getDateTime ("BirthDate");} [csharp] www.2cto. comBinaryFormatter formatter = new BinaryFormatter (); Class1 cls1 = new Class1 (); cls1.Name = "Class1"; cls1.ID = "cls-1"; cls1. SetBirthDate (DateTime. today); using (FileStream stream = new FileStream ("c: \ Class1.bin", FileMode. create, FileAccess. write) {formatter. serialize (stream, cls1);} Class1 cls2 = null; using (FileStream stream = new FileStream ("c: \ Class1.bin", FileMode. open, FileAccess. read) {cls2 = formatter. deserialize (stream) as Class1;} is a class that implements the ISerializable interface. It also requires that the class must implement MingContext context) is a signed constructor called during deserialization. If the constructor is missing, the Class1 object will throw a SerializationException during deserialization. "The constructor to deserialize an object of type 'xxx. class1 'was not found. ". ISerializable interface declaration: [csharp] [ComVisible (true)] public interface ISerializable {[SecurityCritical] void GetObjectData (SerializationInfo, StreamingContext context);} when the ISerializable interface is used by Formatter, the GetObjectData method will be called for serialization. During deserialization, the class Constructor (SerializationInfo information, StreamingContext context) will be called ). Therefore, if Class1 has sub-classes, such as Class2, and Class2 also supports serialization, then Class2 must also implement the GetObjectData method and constructor (SerializationInfo information, StreamingContext context) signature. The following Class2 definition: [csharp] [Serializable] public class Class2: Class1 {public int Age {get; set;} public Class2 () {} protected Class2 (SerializationInfo info, streamingContext context): base (info, context) {this. age = info. getInt32 ("Age");} public override void GetObjectData (SerializationInfo info, StreamingContext context) {base. getObjectData (info, context); info. addValue ("Age", this. age );}} Therefore, when the ISerializable interface is implemented, the GetObjectData method is set to virtual. A constructor (SerializationInfo information, StreamingContext context) signature is required, and the constructor is usually protected.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.