美文网首页
c# 序列化(Serialize)与反序列化(Deseriali

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

作者: _armour | 来源:发表于2019-06-20 21:18 被阅读0次

    序列化又称串行化,是.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)与反序列化(Deseriali

          本文链接:https://www.haomeiwen.com/subject/twtwtctx.html