Serialization of C # Programming basics

Source: Internet
Author: User
Tags soap object serialization
First, the meaning of serialization





Serialization is the process of processing an object into a byte stream to store an object or transfer it to memory, database, or file. Its primary purpose is to preserve the state of the object so that it can be recreated when needed. The reverse process is called deserialization.



1.1 How serialization works



This diagram shows the entire process of serialization.






The object is serialized as a stream. The stream passes not only data, but also information about the object type, such as the version, culture, and assembly name of the object. This stream allows you to store objects in a database, file, or memory.






1.2 for serialization






Serialization allows the developer to save the state of an object and recreate the object as needed to provide storage and exchange of data for the object. With serialization, developers can also perform actions such as sending objects to a remote application through a WEB service, passing objects from one domain to another, passing objects across firewalls as XML strings, or maintaining security or user-specific information across applications.






1.3 Making an object serializable






To serialize an object, you need the object to serialize, the stream to contain the serialized object, and a Formatter. The System.Runtime.Serialization contains the classes required to serialize and deserialize the object.






Applying the SerializableAttribute attribute to a type can indicate that an instance of the type can be serialized. When trying to serialize, a SerializationException exception is thrown if the type has no SerializableAttribute attribute.






If you do not want the fields in your class to be serializable, apply the NonSerializedAttribute attribute. If a field of a serializable type contains pointers, handles, or other data structures that are specific to a particular environment, and cannot be rebuilt in a meaningful way in a different environment, you may want to make the field non-serializable.






If a serialized class contains a reference to an object of another class that is marked as SerializableAttribute, the objects are also serialized.






1.3.1 binary serialization and XML serialization






You can use either binary serialization or XML serialization. In binary serialization, all members, even those that are read-only, are serialized to improve performance. XML serialization provides better readability of code and provides greater flexibility in object sharing and use for interoperability.






1.3.2 binary serialization






Binary serialization uses binary encoding to generate thin serialization for storage or socket-based network flow, and so on.






1.3.3 XML Serialization






XML serialization serializes the public fields and properties of an object or the parameters and return values of a method into an XML stream that conforms to a particular XML Schema definition language (XSD) document. XML serialization generates a strongly typed class with public properties and fields that are converted to XML. The System.Xml.Serialization contains the classes required to serialize and deserialize Xml.






You can apply attributes to classes and class members to control how XmlSerializer serializes or deserializes class instances.






1.3.4 SOAP Serialization






XML serialization can also be used to serialize an object into an XML stream that conforms to the SOAP specification. SOAP is an XML-based protocol that is specifically designed to use XML to transfer procedure calls. As with regular XML serialization, attributes can be used to control the text-style SOAP messages generated by the XML Web services.






1.3.5 basic serialization and custom serialization






Serialization can be performed in two ways: basic serialization and custom serialization. Basic serialization uses the. NET Framework to customize the serialization of objects.






Basic serialization of 1.3.5.1






The only requirement for basic serialization is that the object must apply the SerializableAttribute attribute.






NonSerializedAttribute can be used to suppress the serialization of specific fields.






When using basic serialization, versioning of objects can cause problems, in which case custom serialization may be more appropriate. Basic serialization is the simplest way to perform serialization, but does not provide much control over the process.



1.3.5.2 Custom Serialization



In custom serialization, you can specify exactly which objects will be serialized and how to complete serialization. The class must be marked as SerializableAttribute and implement the ISerializable interface.



You must use a custom constructor if you want to also deserialize the object in a custom manner.



1.3.6 Designer Sequence



Designer serialization is a special form of serialization that involves the kind of object persistence that is typically associated with a development tool. Designer serialization is the process of converting an object graph into a source file that you can later use to restore the object graph. The source file can contain code, markup, and even SQL table information. For more information, see Designer Serialization Overview.



Ii. saving Object data by serialization



Although you can set the properties of an object to the default value at design time, if the object is damaged, all values entered at run time are lost. You can use serialization to persist object data between instances, so that you can store values and retrieve them the next time you instantiate an object.



In this walkthrough, you will create a simple object and save the object's data to a file. Then, when you re-create the object, the data is retrieved from the file. Finally, the code is modified to persist the object using the SOAP format.



2.1 Saving objects using serialization


[Serializable] // Mark the class as serializable
    public class Coupon: INotifyPropertyChanged
    {
        public decimal Amount {get; set;}
        public float InterestRate {get; set;}
        public int Term {get; set;}
        private string _name;
        public string Name
        {
            get {return _name;}
            set
            {
                _name = value;
                PropertyChanged? .Invoke (this, new PropertyChangedEventArgs ("Customer"));
            }
        }
        [field: NonSerialized ()] // Mark a field in the serializable class as not serializable
        public event PropertyChangedEventHandler PropertyChanged;
        public Coupon (decimal amount, float interestRate, int term, string name)
        {
            Amount = amount;
            InterestRate = interestRate;
            Term = term;
            _name = name;
        }
    }
static void Main (string [] args)
{
            const string fileName = @ "demo1.txt";
            var coupon = new Coupon (10000, 0.2f, 1, "Reverse Bones");

            using (var stream = File.Create (fileName))
            {
                var deserializer = new BinaryFormatter (); // Binary Format Serializer
                deserializer.Serialize (stream, coupon); // Serialize the object to a file
            }
}





Now try deserializing to see if the value of the previous Coupon object is consistent.


static void Main (string [] args)
{
            const string fileName = @ "demo1.txt";
            // var coupon = new Coupon (10000, 0.2f, 1, "Anti bone");
            // Determine if the file exists
            if (! File.Exists (fileName))
            {
                return;
            }
            using (var stream = File.OpenRead (fileName))
            {
                var deserializer = new BinaryFormatter (); // binary serializer
                var coupon = deserializer.Deserialize (stream) as Coupon; // Deserialize
                if (coupon == null)
                {
                    return;
                }
                Console.WriteLine ($ "{nameof (Coupon)}:");
                Console.WriteLine ($ "{nameof (coupon.Amount)}: {coupon.Amount}");
                Console.WriteLine ($ "{nameof (coupon.InterestRate)}: {coupon.InterestRate}%");
                Console.WriteLine ($ "{nameof (coupon.Term)}: {coupon.Term}");
                Console.WriteLine ($ "{nameof (coupon.Name)}: {coupon.Name}");
            }
            Console.Read ();
}








2.2 Saving objects using SOAP format


static void Main (string [] args)
{
             const string fileName = @ "demo1.txt";
             var coupon = new Coupon (10000, 0.2f, 1, "Reverse Bones");
             using (var stream = File.Create (fileName))
             {
                 var deserializer = new SoapFormatter (); // Soap formatter
                 deserializer.Serialize (stream, coupon); // Serialize
             }
}





SoapFormatter is also used when deserializing


var deserializer = new SoapFormatter (); // Soap formatter
var coupon = deserializer.Deserialize (stream) as Coupon; // deserialize 


"Note" This example stores data in a binary or SOAP-formatted file. These formats should not be used for sensitive data, such as passwords or credit card information.






The memo binary format is appropriate for most Windows applications. But for Web applications or Web services, you might want to use SOAP format to save objects to an XML file so that objects are easy to share.






Similarly, object serialization can be saved in an XML file by XmlSerializer. We can choose the appropriate serializer according to the requirements, the operation is basically the same.



The above is the C # programming basis of the serialized content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!


  • 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.