[C #] just to briefly describe serialization,

Source: Internet
Author: User

[C #] just to briefly describe serialization,
Just to put it simply, serialization

[Master] Anti-bone Zi (original address] http://www.cnblogs.com/liqingwen/p/5902005.html

Directory
  • Meaning of serialization
  • Save object data through serialization
  • Different Opinions

 

1. serialization meaning serialization refers to processing objects as byte streams to store objects or transmit them to memory, databases, or files. The main purpose is to save the object state so that you can recreate the object as needed. The opposite process is called deserialization. 1.1 serialization method of work this figure shows the whole serialization process. Figure 1.1-1

The object is serialized as a stream. A stream transmits not only data, but also information about the object type, such as the object version, culture, and assembly name. This stream stores objects in databases, files, or memory. 1.2 used for serialization through serialization, developers can save the object state, and re-create the object as needed, so as to provide object storage and data exchange. Through serialization, developers can also perform operations similar to the following: objects are sent to remote applications through Web Services, objects are transferred from one domain to another, and objects are transferred across firewalls in the form of XML strings, you can also maintain security information or user-specific information across applications. 1.3 enable Object serialization if you want to serialize an object, you need to serialize the object, the stream containing the serialized object, and a Formatter. System. Runtime. Serialization Contains classes required for Serialization and deserialization of objects. Apply the SerializableAttribute attribute to a type that indicates that instances of this type can be serialized. If the type does not have the SerializableAttribute attribute during serialization, A SerializationException is thrown. If you do not want to serialize fields in the class, apply the NonSerializedAttribute feature. If serializable fields contain pointers, handles, or other data structures dedicated to specific environments, and cannot be reconstructed in a meaningful way in different environments, this field may not be serialized. If the serialized class contains references to objects of other classes marked as SerializableAttribute, these objects will also be serialized. 1.3.1 binary serialization and XML serialization can be performed using binary serialization or XML serialization. In binary serialization, all members (even those read-only members) are serialized to improve performance. XML serialization provides code with better readability and greater flexibility in object sharing and usage for interoperability. 1.3.2 binary serialization uses binary encoding to generate streamlined serialization for storage or socket-based network streams. 1.3.3 XML serialization serializes the parameters and return values of common fields and attributes of objects or methods into XML streams that comply with the specific XML Schema Definition Language (XSD) documentation. XML serialization generates a strong type class with common attributes and fields converted to XML. System. Xml. Serialization Contains classes required for Serialization and deserialization of XML. You can apply features to classes and Class Members to control how XmlSerializer serializes or deserializes class instances. 1.3.4 XML serialization of SOAP serialization can also be used to serialize objects into XML streams conforming to SOAP specifications. SOAP is an XML-based protocol designed specifically for the use of XML for transfer process calls. Like conventional XML serialization, this feature can be used to control SOAP messages of text styles generated by XML Web services. 1.3.5 basic serialization and custom serialization can be performed in two ways: Basic serialization and custom serialization. The. NET Framework is used for basic serialization to automatically serialize objects. 1.3.5.1 basic serialization

The only requirement for basic serialization is that the object must apply the SerializableAttribute feature. NonSerializedAttribute can be used to disable serialization of specific fields.

When using basic serialization, Version Control of the object may cause problems. In this case, custom serialization may be more appropriate. Basic serialization is the simplest way to execute serialization, but it does not provide much control over the process. 1.3.5.2 custom serialization in custom serialization, You can accurately specify the objects to be serialized and how to complete the serialization. Class must be marked as SerializableAttribute and implement the ISerializable interface. If you want to deserialize an object in a custom way, you must use a custom constructor. 1.3.6 designer serialization is a special type of serialization that involves the persistence of objects that are usually associated with development tools. The designer serialization is the process of converting an object graph into a source file that can be used to restore the object graph. The source file can contain code, tags, and even SQL table information. For more information, see Designer Serialization Overview. Ii. Save object data through serialization. Although you can set the property of an object as the default value during design, if the object is damaged, all input values will be lost at runtime. You can use serialization to keep object data between instances, so that you can store values and retrieve these values at the next Object Instantiation. In this walkthrough, you create a simple object and save the data of the object to a file. Then, when you recreate an object, the data will be retrieved from the file. Finally, the modified code is used to maintain the object in the SOAP format. 2.1 use serialization to save object 1 [Serializable] // mark the class as Serializable 2 public class Coupon: INotifyPropertyChanged 3 {4 public decimal Amount {get; set ;} 5 6 public float InterestRate {get; set;} 7 8 public int Term {get; set;} 9 10 private string _ name; 11 12 public string Name13 {14 get {return _ name;} 15 set16 {17 _ name = value; 18 PropertyChanged ?. Invoke (this, new PropertyChangedEventArgs ("Customer"); 19} 20} 21 22 [field: NonSerialized ()] // mark a field in the serializable class as not serialized 23 public event PropertyChangedEventHandler PropertyChanged; 24 25 public Coupon (decimal amount, float interestRate, int term, string name) 26 {27 Amount = amount; 28 InterestRate = interestRate; 29 Term = term; 30 _ name = name; 31} 32}Coupon. cs
1 static void Main (string [] args) 2 {3 const string fileName = @ "demo1.txt"; 4 var coupon = new Coupon (10000, 0.2f, 1, "reverse bone"); 5 6 using (var stream = File. create (fileName) 7 {8 var deserializer = new BinaryFormatter (); // binary format serializer 9 deserializer. serialize (stream, coupon); // Serialize the object to the file 10} 11}
Figure 2-1

 

Now try deserialization to see if the value of the Coupon object is consistent with that of the previous Coupon object.

1 static void Main (string [] args) 2 {3 const string fileName = @ "demo1.txt"; 4 // var coupon = new Coupon (10000, 0.2f, 1, "Anti-bone"); 5 6 // determine whether the file exists 7 if (! File. exists (fileName) 8 {9 return; 10} 11 12 using (var stream = File. openRead (fileName) 13 {14 var deserializer = new BinaryFormatter (); // binary serializer 15 var coupon = deserializer. deserialize (stream) as Coupon; // deserialization 16 17 if (coupon = null) 18 {19 return; 20} 21 22 Console. writeLine ($ "{nameof (Coupon)}:"); 23 Console. writeLine ($ "{nameof (coupon. amount) }:{ coupon. amount} "); 24 Console. writeLine ($ "{nameof (coupon. interestRate) }:{ coupon. interestRate} % "); 25 Console. writeLine ($ "{nameof (coupon. term) }:{ coupon. term} "); 26 Console. writeLine ($ "{nameof (coupon. name) }:{ coupon. name} "); 27} 28 29 Console. read (); 30}

Figure 2-2

 

2.2 save objects in SOAP format
1 static void Main (string [] args) 2 {3 const string fileName = @ "demo1.txt"; 4 var coupon = new Coupon (10000, 0.2f, 1, "reverse bone"); 5 6 using (var stream = File. create (fileName) 7 {8 var deserializer = new SoapFormatter (); // Soap formatter 9 deserializer. serialize (stream, coupon); // Serialize 10} 11}

Figure 2-3

SoapFormatter is also used for deserialization. The result is the same as Figure 2-2.

Var deserializer = new SoapFormatter (); // var coupon = deserializer. Deserialize (stream) as Coupon; // deserialization

[Note] in this example, data is stored in binary or SOAP files. These formats should not be used for sensitive data, such as passwords or credit card information.

[Note] binary format is applicable to most Windows applications. However, for Web applications or Web services, you may want to save the object to an XML file in the SOAP format to make it easier to share the object.

Similarly, you can use XmlSerializer to serialize and save objects in XML files. We can select an appropriate serializer as needed, and the operations are basically the same.

 

Different Opinions

@ Hi when using the SerializableAttribute feature for childhood, automatic attributes are not recommended. The serialized fields are more than k_BackingField <> 17 characters. if the object is a waste of traffic, we recommend that you use DataContractAttribute and DataMemberAttribute.

@ Liang yichen: unless the other party's system requires SOAP to communicate with each other, everyone should resist such anti-virus things. We recommend that you use JSON or Protobuf.

 

[Reference] Microsoft official documentation

 

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.