C# 之二进制序列化

序列化:又称串行化,是.NET运行时环境用来支持用户定义类型的流化的机制。其目的是以某种存储形成使自定义对象持久化,或者将这种对象从一个地方传输到另一个地方。

一般有三种方式:1、是使用BinaryFormatter进行串行化二进制序列化;2、使用XmlSerializer进行串行化的XML序列化;3、使用SOAP协议进行序列化。这里先总结二进制序列化。

命名空间:

System.Runtime.Serialization.Formatters.Binary;
System.IO;

1).先建一个可序列化的类

  [Serializable]     
   class Person
    {
private string name; public string Name { get { return name; } set { name = value; } }
[NonSerialized]
//age这个字段不序列化 private int age; public int Age { get { return age; } set { age = value; } }
public Person() { } public Person(string name ,int age)
  {
this.name = name; this.age = age; } public void say()
  { Console.WriteLine(
"hello,my name is{0} ,I am {1}years old.",name,age); }
}

Main函数里:

static void Main(string[] args)
        {
            List<Person> persons = new List<Person>();
            Person p1 = new Person("chen", 24);
            Person p2 = new Person("li", 23);
            persons.Add(p1);
            persons.Add(p2);

            xuliehua(persons); //调用静态序列化方法
            fanxuliehua();       //调用静态反序列化方法


            Console.ReadKey();
        }

        public static void xuliehua(List<Person> persons)//序列化方法
        {
            FileStream fs = new FileStream("Person.bin", FileMode.Create);//创建一个文件流,对文件进行写入
            BinaryFormatter bf = new BinaryFormatter();//使用CLR二进制格式器
            bf.Serialize(fs, persons); //序列化到硬盘
            fs.Close();//关闭文件流
        }

        public static void fanxuliehua()//反序列化方法
        {

            FileStream fs = new FileStream("Person.bin", FileMode.Open);//打开流文件
            BinaryFormatter bf = new BinaryFormatter();
            List<Person> persons = bf.Deserialize(fs) as List<Person>;//从硬盘反序列化  

            //或  Person p=(Person)bf.Deserialize(fs); 对应上面的或者

            fs.Close();//关闭文件流
            for (int i = 0; i < persons.Count; i++)
            {
                persons[i].say();
            }
        }

结果:

name 序列化过,而 age没有序列化,所以为0。

原文地址:https://www.cnblogs.com/jiangshuai52511/p/7793505.html