二进制序列化

1.概要

  • 二进制序列化对象时,
  • 对象所对应的class必须被标记为[Serializable]
  • 对象的所有字段的类型必须被标记为[Serializable]
  • Object类默认被标记为可序列化
  • 但是对象方法中存在未被标记的类型时,此类型不用标记[Serializable]
  • 被标记序列化的类的字段如果不想被序列化,就标记[NonSerialized]
    ->但是必须标记到字段上,不能标记到属性上

2.代码

class Program
{
    static void Main()
    {
        People people = new People();
        people.age = 20;
        people.Name = "A";
        people.Email = "abc@qq.com";
        
        //二进制 序列化 就是把对象变成流的过程,把对象变成byte
        //创建序列化器
        //

        BinaryFormatter binaryFormatter = new BinaryFormatter();
        //开始执行序列化
        using (FileStream fs  = new FileStream("Person,bin",FileMode.Create))
        {
            binaryFormatter.Serialize(fs, people);
        }
        Console.WriteLine("序列化完毕");
    }

}

[Serializable]
public class People
{

    [NonSerialized]
    private string _name;
    public string Name 
    { 
        get { return _name; }
        set { _name = value; }
    }

    public int age { get; set; }
    public string Email { get; set; }
}

3.反序列化

反序列化的时候必须引用被序列化的类型所在的程序集

class Program
{
    static void Main()
    {
        People people = new People();
        people.age = 20;
        people.Name = "A";
        people.Email = "abc@qq.com";
        
        //二进制 序列化 就是把对象变成流的过程,把对象变成byte
        //创建序列化器
        //

        BinaryFormatter binaryFormatter = new BinaryFormatter();
        //开始执行序列化
        using (FileStream fs  = new FileStream("Person,bin",FileMode.Create))
        {
            binaryFormatter.Serialize(fs, people);
        }
        Console.WriteLine("序列化完毕");

        //反序列化
        using (FileStream bf = new FileStream("Person,bin",FileMode.Open))
        {
            object obj = binaryFormatter.Deserialize(bf);
            Console.WriteLine($"{((People)obj).Name},
                    {((People)obj).Email},{((People)obj).age}");
        }
    }
}

[Serializable]
public class People
{

    [NonSerialized]
    private string _name;
    public string Name 
    { 
        get { return _name; }
        set { _name = value; }
    }

    public int age { get; set; }
    public string Email { get; set; }
}
此条目发表在C#分类目录。将固定链接加入收藏夹。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注