编程语言
首页 > 编程语言> > C#序列化与反序列化

C#序列化与反序列化

作者:互联网

序列化:将对象转为二进制

反序列化:将二级制转为对象

作用:传输数据

一个类如果想要被序列化,需要在该类上面加上[Serializable],例如下面的Person类:

[Serializable]
class Person
{
    string _name;
    int _age;

    public string Name { get => _name; set => _name = value; }
    public int Age { get => _age; set => _age = value; }
}

序列化需要通过类BinaryFormatter来实现,例如声明对象后,将对象进行序列化,代码如下:

Person p = new Person();
p.Name = "小李";
p.Age = 12;

using (FileStream fsWrite = new FileStream(@"C:\Users\One\Desktop\123.txt", FileMode.OpenOrCreate, FileAccess.Write))
{
    BinaryFormatter bf = new BinaryFormatter();
    bf.Serialize(fsWrite, p);  //将p对象序列化
}

通过文件流将对象p写入到文件123.txt中

反序列化

Person p2;
using (FileStream fsRead = new FileStream(@"C:\Users\One\Desktop\123.txt", FileMode.Open, FileAccess.Read))
{
    BinaryFormatter bf = new BinaryFormatter();
    p2 = (Person)bf.Deserialize(fsRead);  //将p对象序列化
}

 

本例子全部代码

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

namespace 序列化和反序列化
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person();
            p.Name = "小李";
            p.Age = 12;

            using (FileStream fsWrite = new FileStream(@"C:\Users\One\Desktop\123.txt", FileMode.OpenOrCreate, FileAccess.Write))
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(fsWrite, p);  //将p对象序列化
            }

            //反序列化
            Person p2;
            using (FileStream fsRead = new FileStream(@"C:\Users\One\Desktop\123.txt", FileMode.Open, FileAccess.Read))
            {
                BinaryFormatter bf = new BinaryFormatter();
                p2 = (Person)bf.Deserialize(fsRead);  //将p对象序列化
            }

            Console.WriteLine("name = {0}", p2.Name);
            Console.WriteLine("age = {0}", p2.Age);

            Console.ReadKey();
        }
    }

    [Serializable]
    class Person
    {
        string _name;
        int _age;

        public string Name { get => _name; set => _name = value; }
        public int Age { get => _age; set => _age = value; }
    }
}

 

标签:bf,C#,Person,new,BinaryFormatter,序列化,FileStream
来源: https://blog.51cto.com/u_12570763/2847871