Shenzhen Ka Wah Road _06 _ architect advanced serialization

What is serialized

Serialized, serialization It is also known, is the .NET runtime environment to support user-defined type fluidization mechanism. Serialization is to save an object to a file or database field to go, deserialization is at the appropriate time this document reconverted to the original object use. Its purpose is to form some kind of memory so that the custom objects persistent, or such objects from one place to another.

.NET supports object serialization in several ways

Binary Serialization : After the object is serialized binary form, achieved by BinaryFormatter class, which is located in the System.Runtime.Serialization.Formatters.Binary namespace.

Serialization SOAP : Results after Object Serialization SOAP protocol compliance, i.e. it is transmitted through the SOAP protocol, under the category by SoapFormatter System.Runtime.Serialization.Formatters.Soap namespace implemented.

XML serialization : Results after the object is serialized XML form, achieved by XmlSerializer class, which is located in the System.Xml.Serialization namespace. XML serialization can not serialize private data.

Several sequences of the difference

Binary format and SOAP formats can serialize all serializable field of a type, whether it is public or private field field. XML serialization format only public fields or public property has a private field, open the properties of private fields will not be ignored by.

When using a binary serialization format, it is not only the field of the data object to be persistent, and persistent fully qualified name, and full name is defined for each type of assembly (including packets that version, public key token, regional) , a binary format is performed such that the data will be checked for type deserialization. SOAP serialization format by using XML namespaces to persist original assembly information. The XML serialization format does not save the full type name or assembly information. This is a more convenient form of XML data terminal openness. If you want to extend the persistent object map range as possible, SOAP and XML format format is ideal.

Using the characteristics of the control sequences

Make a .Net object supports serialization service, the user must add [the Serializable] characteristics associated with each class. If some members are not suitable class of sequences which are involved (for example: password field) can be added [the NonSerialized] properties before these fields.

2. binary serialization and deserialization

(1) binary serialization and deserialization Program Example   

    [Serializable]  //必须添加序列化特性
    public class Person
    {
        private string Name;//姓名
        private bool Sex;//性别,是否是男
        public Person(string name, bool sex)
        {
            this.Name = name;
            this.Sex = sex;
        }
        public override string ToString()
        {
            return "姓名:" + this.Name + "\t性别:" + (this.Sex ? "男" : "女");
        }
    }

    [Serializable]  //必须添加序列化特性
    public class Programmer : Person
    {
        private string Language;//编程语言
        public Programmer(string name, bool sex, string language) : base(name, sex)
        {
            this.Language = language;
        }
        public override string ToString()
        {
            return base.ToString() + "\t编程语言:" + this.Language;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //创建Programmer列表,并添加对象
            List<Programmer> list = new List<Programmer>();
            list.Add(new Programmer("李志伟", true, "C#"));
            list.Add(new Programmer("Coder2", false, "C++"));
            list.Add(new Programmer("Coder3", true, "Java"));

            //使用二进制序列化对象
            string fileName = @"D:\users\lizw\桌面\Programmers.dat";//文件名称与路径
            Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
            BinaryFormatter binFormat = new BinaryFormatter();//创建二进制序列化器
            binFormat.Serialize(fStream, list);
            //使用二进制反序列化对象
            list.Clear();//清空列表
            fStream.Position = 0;//重置流位置
            list = (List<Programmer>)binFormat.Deserialize(fStream);//反序列化对象
            foreach (Programmer p in list)
            {
                Console.WriteLine(p);
            }
            Console.Read();
        }
    }

to sum up

Binary serialization must be serialized for each of the classes and their associated class plus [the Serializable] characteristics, does not require class members can use the sequence of [the NonSerialized] characteristics.

All members serializing binary object class can be serialized (including private), and the presence or absence of class constructor does not require parameters.

When using a binary serialization format, it is not only the field of the data object to be persistent, and persistent fully qualified name, and full name is defined for each type of assembly (including packets that version, public key token, regional) , a binary format is performed such that the data will be checked for type deserialization. So when the operating environment deserialized to the serialization runtime environment to the same, whether the person may not deserialize success.

Mode using SOAP serialization and deserialization

(1) SOAP serialization and deserialization Program Example   

    [Serializable]  //必须添加序列化特性
    public class Person
    {
        private string Name;//姓名
        private bool Sex;//性别,是否是男
        public Person(string name, bool sex)
        {
            this.Name = name;
            this.Sex = sex;
        }
        public override string ToString()
        {
            return "姓名:" + this.Name + "\t性别:" + (this.Sex ? "男" : "女");
        }
    }

    [Serializable]  //必须添加序列化特性
    public class Programmer : Person
    {
        private string Language;//编程语言
        public Programmer(string name, bool sex, string language) : base(name, sex)
        {
            this.Language = language;
        }
        public override string ToString()
        {
            return base.ToString() + "\t编程语言:" + this.Language;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //实例化对象
            Programmer p = new Programmer("李志伟", true, "C、C#、C++、Java");
            //使用SOAP序列化对象
            string fileName = @"D:\users\lizw\桌面\Programmers.xml";//文件名称与路径
            Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
            SoapFormatter soapFormat = new SoapFormatter();//创建SOAP序列化器
            soapFormat.Serialize(fStream, p);//SOAP不能序列化泛型对象
            //使用SOAP反序列化对象
            fStream.Position = 0;//重置流位置
            p = null;
            p = (Programmer)soapFormat.Deserialize(fStream);
            Console.WriteLine(p);
            Console.Read();

        }
    }

to sum up

SOAP sequence of binary sequence of difference is: SOAP sequence of the generic type can not be serialized. No need to specify the type of object in the sequence of the sequence with the sequences of the same binary serialization. And specify the type of XML serialization of a serialized object to XML serializer.

Way to use XML serialization and de-serialization

(1) XML serialization and deserialization exemplary procedure    

    public class Person
    {
        public string Name;//姓名
        public bool Sex;//性别,是否是男
        public Person() { }//必须提供无参构造器,否则XmlSerializer将出错

        public Person(string name, bool sex)
        {
            this.Name = name;
            this.Sex = sex;
        }
        public override string ToString()
        {
            return "姓名:" + this.Name + "\t性别:" + (this.Sex ? "男" : "女");
        }
    }

    public class Programmer : Person
    {

        public string Language;//编程语言
        public Programmer() { }//必须提供无参构造器,否则XmlSerializer将出错
        public Programmer(string name, bool sex, string language) : base(name, sex)
        {
            this.Language = language;
        }
        public override string ToString()
        {
            return base.ToString() + "\t编程语言:" + this.Language;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //创建Programmer列表,并添加对象
            List<Programmer> list = new List<Programmer>();
            list.Add(new Programmer("李志伟", true, "C#"));
            list.Add(new Programmer("Coder2", false, "C++"));
            list.Add(new Programmer("Coder3", true, "Java"));
            //使用XML序列化对象
            string fileName = @"D:\users\lizw\桌面\Programmers.xml";//文件名称与路径
            Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
            XmlSerializer xmlFormat = new XmlSerializer(
            typeof(List<Programmer>),
            new Type[] { typeof(Programmer), typeof(Person) }
            );//创建XML序列化器,需要指定对象的类型
            xmlFormat.Serialize(fStream, list);
            //使用XML反序列化对象
            fStream.Position = 0;//重置流位置
            list.Clear();
            list = (List<Programmer>)xmlFormat.Deserialize(fStream);
            foreach (Programmer p in list)
            {
                Console.WriteLine(p);
            }
            Console.Read();
        }
    }

to sum up

When using XML serialization or deserialization, the sequence needs to specify the type of object and its associated type for XML serializer.

XML serialization of a serialized object only public property, if the objects have a constructor with no arguments, whether the person can not be deserialized.

[Serializable] and [NonSerialized] characteristics of XML serialization is invalid! There is no need to increase the target [the Serializable] characteristics when using XML serialization.

 

Published 37 original articles · won praise 3 · Views 6314

Guess you like

Origin blog.csdn.net/huan13479195089/article/details/104830944