C#序列化特性继承问题

测试对象 ‘BinaryFormatter’ 'XmlSerializer'
结论:

BinaryFormatter:父类有序列化标签时,子类序列化也需要添加序列化标签
XmlSerializer:父类有序列化标签时,子类序列化可以不用添加序列化标签

定义父类

[Serializable]
public class TestSerializer
{
        public string Name { set; get; }

        public string Value { set; get; }
}

定义子类

[Serializable]
public class SubTestSerializer : TestSerializer
{
        public int Index { set; get; } = 0;

        public bool Enabled { set; get; } = false;
}

序列化测试

  1. 声明对象
SubTestSerializer seri = new SubTestSerializer() { Name = "T1", Value = "V1" ,Index=100,Enabled=true};
  1. BinaryFormatter测试
            string str = "";
            BinaryFormatter xmlSerializer = new BinaryFormatter();
            using (MemoryStream stream = new MemoryStream())
            {
                xmlSerializer.Serialize(stream, seri);
                str = Convert.ToBase64String(stream.ToArray());
            }

            BinaryFormatter xmlSerializer1 = new BinaryFormatter();
            byte[] buffer = Convert.FromBase64String(str);
            using (MemoryStream stream1 = new MemoryStream(buffer))
            {
                var seri1 = (SubTestSerializer)xmlSerializer1.Deserialize(stream1);
            }

当子类无[Serializable]特性时报错,提示缺少序列化标记,序列化失败,说明BinaryFormatter只能针对具有[Serializable]特性的对象序列化,当父类有[Serializable]标记时,子类也需要添加。

  1. XmlSerializer测试
            string str="";
            XmlSerializer xmlSerializer2 = new XmlSerializer(typeof(SubTestSerializer));
            using (MemoryStream stream = new MemoryStream())
            {
                xmlSerializer2.Serialize(stream, seri);
                str = Convert.ToBase64String(stream.ToArray());
            }

            XmlSerializer xmlSerializer3 = new XmlSerializer(typeof(SubTestSerializer));
            byte[] buffer2 = Convert.FromBase64String(str);
            using (MemoryStream stream1 = new MemoryStream(buffer2))
            {
                var seri1 = (SubTestSerializer)xmlSerializer3.Deserialize(stream1);
            }

当子类无[Serializable]特性时,可以正常执行序列化操作。所以XmlSerializer序列化对象时,父类有[Serializable]特性时,子类可以不添加。

posted on 2023-01-11 15:56  挖穿地球😁  阅读(205)  评论(0编辑  收藏  举报