c# 序列化(Serialize)与反序列化(Deserialize)

序列化又称串行化,是.NET运行时环境用来支持用户定义类型的流化的机制。
其目的是以某种存储形式使自定义对象持久化(Unity-Inspector),或者将这种对象从一个地方传输到另一个地方(网络传输)。
.NET框架提供了两种串行化的方式:

  • BinaryFormatter(提供了一个简单的二进制数据流以及某些附加的类型信息)
  • XmlSerializer(将数据流格式化为XML存储)

标签

  • 序列化 [Serializable]
  • 反序列化 [NonSerialized] [XmlIgnore]

定义一个Person结构

[Serializable]
public class Person
{
    public string name;
    public int age;
    public override string ToString()
    {
        return "name:" + name + " age:" + age;
    }
}

XmlSerializer

        var person = new Person();
        person.name = "小猪";
        person.age = 20;
        print(person.ToString());
        using (var fs = new FileStream("person.bin", FileMode.Create)) {
            var xs = new XmlSerializer(typeof(Person));
            xs.Serialize(fs, person);
        }
        Person p;
        using(var fs = new FileStream("person.bin", FileMode.Open)) {
            var xs = new XmlSerializer(typeof(Person));
            p = xs.Deserialize(fs) as Person;
        }
        print(p.ToString());

BinaryFormatter

        var person = new Person();
        person.name = "小猪";
        person.age = 20;
        print(person.ToString());
        using (var fs = new FileStream("person2.bin", FileMode.Create)) {
            var bf = new BinaryFormatter();
            bf.Serialize(fs, person);
        }
        Person p;
        using (var fs = new FileStream("person2.bin", FileMode.Open)) {
            var bf = new BinaryFormatter();
            p = bf.Deserialize(fs) as Person;
        }
        print(p.ToString());

你可能感兴趣的:(c# 序列化(Serialize)与反序列化(Deserialize))