Home > Backend Development > C#.Net Tutorial > Serialization of C# programming basics

Serialization of C# programming basics

黄舟
Release: 2017-02-06 16:49:26
Original
1839 people have browsed it

1. The meaning of serialization

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

1.1 How serialization works

This figure shows the entire process of serialization.

Serialization of C# programming basics

Objects are serialized into streams. Streams pass not only data but also information about the object type, such as the object's version, culture, and assembly name. Through this stream, objects can be stored in a database, file, or in memory.

1.2 For serialization


Through serialization, developers can save the state of an object and recreate it when needed This object provides object storage and data exchange. Serialization also enables developers to do things like send objects to remote applications through Web services, pass objects from one domain to another, pass objects as XML strings across firewalls, or across applications. The program maintains security information or user-specific information.

1.3 Make the object serializable


To serialize the object, you need the object to be serialized and the sequence to be included. Stream of objects, and a Formatter. System.Runtime.Serialization contains classes required to serialize and deserialize objects.


Applying the SerializableAttribute attribute to a type indicates that instances of the type can be serialized. When trying to serialize, if the type does not have the SerializableAttribute attribute, a SerializationException will be thrown.


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 a pointer, handle, or some other data structure that is specific to a particular environment and cannot be reconstructed in a meaningful way in a different environment, you may need to make the field non-serializable.


If the serialized class contains references to objects of other classes marked with the SerializableAttribute, these objects will also be serialized.

1.3.1 Binary serialization and XML serialization


You can use binary serialization or XML serialization. In binary serialization, all members are serialized (even those that are read-only), which can improve performance. XML serialization provides more readable code and greater flexibility in object sharing and use for interoperability.

1.3.2 Binary serialization


Binary serialization uses binary encoding to generate a streamlined serialization for storage Or socket based network streaming etc.

1.3.3 XML serialization


##XML serialization converts the public fields and properties of the object or the parameters and return values ​​of the method Serialized into an XML stream that conforms to a specific XML Schema Definition Language (XSD) document. XML serialization produces a strongly typed class with public properties and fields that are converted to XML. 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 objects into an XML stream that conforms to the SOAP specification. . SOAP is an XML-based protocol designed specifically for transporting procedure calls using XML. Like regular XML serialization, attributes can be used to control the text-style SOAP messages generated by 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 automatically serialize objects.


1.3.5.1 Basic serialization


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


#NonSerializedAttribute can be used to disable serialization of specific fields.


Versioning of objects may cause problems when using basic serialization, 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 the serialization is done. Classes must be marked with SerializableAttribute and implement the ISerializable interface.

If you want to deserialize the object in a custom way as well, you must use a custom constructor.

1.3.6 Designer Serialization

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

2. Save object data through serialization

Although you can set the properties of an object to default values ​​at design time, if the object is damaged, all values ​​entered at runtime will be lost. will be lost. You can use serialization to persist object data between instances, enabling values ​​to be stored and retrieved the next time the object is instantiated.

In this walkthrough, you will create a simple object and save the object's data to a file. The data will then be retrieved from this file when you recreate the object. Finally, you'll modify the code to persist the object using SOAP format.

2.1 Save the object using serialization

   [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()]    //将可序列化的类中的某字段标记为不被序列化
        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, "反骨仔");

            using (var stream = File.Create(fileName))
            {
                var deserializer = new BinaryFormatter();  //二进制格式序列化器
                deserializer.Serialize(stream, coupon);  //序列化对象到文件中
            }
}
Copy after login

Serialization of C# programming basics

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

static void Main(string[] args)
{
            const string fileName = @"demo1.txt";
            //var coupon = new Coupon(10000, 0.2f, 1, "反骨仔");
            //判断该文件是否存在
            if (!File.Exists(fileName))
            {
                return;
            }
            using (var stream = File.OpenRead(fileName))
            {
                var deserializer = new BinaryFormatter();   //二进制序列化器
                var coupon = deserializer.Deserialize(stream) as Coupon;    //反序列化
                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();
}
Copy after login


Serialization of C# programming basics

2.2 Use SOAP format to save objects

static void Main(string[] args)
{
            const string fileName = @"demo1.txt";
            var coupon = new Coupon(10000, 0.2f, 1, "反骨仔");
            using (var stream = File.Create(fileName))
            {
                var deserializer = new SoapFormatter(); //Soap 格式化器
                deserializer.Serialize(stream, coupon); //序列化
            }
}
Copy after login

Serialization of C# programming basics

Deserialization SoapFormatter can also be used

var deserializer = new SoapFormatter();   //Soap 格式化器
var coupon = deserializer.Deserialize(stream) as Coupon;    //反序列化
Copy after login

[Note] This example stores data in binary or SOAP format files. These formats should not be used for sensitive data such as passwords or credit card information.


#【Note】The binary format is suitable for most Windows applications. But for a Web application or Web service, you may want to save the object to an XML file using SOAP format to make the object easy to share.


Similarly, objects can also be serialized and saved in XML files through XmlSerializer. We can choose the appropriate serializer according to our needs, and the operation is basically the same.

The above is the content of serialization based on C# programming. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template