繁体   English   中英

DataContract序列化(继承)

[英]DataContract Serialization (inheritance)

我知道有很多与此类似的问题,但是经过数小时的搜索,我仍然没有找到答案。 我希望使用Person类的字段序列化Child对象。 这是代码:

    [DataContract]
    abstract class Person
    {
        [DataMember]
        protected int level;

        [DataMember]
        protected string name;

        public Person(int level, string name)
        {
            this.level = level;
            this.name = name;
        }
    }

    [DataContract]
    [KnownType(typeof(Child))] //With and without it\\
    class Child : Person
    {
        public Child(int level, string name) : base(level , name) {}
    }

    class Program
    {
        static void Main(string[] args)
        {
            //CREATE OBJECTS
            List<Person> p = new List<Person>();
            Person p1 = new Child(3, "ned"); p1.Display();
            Person p2 = new Child(5, "rob"); p2.Display();
            p.Add(p1); p.Add(p2);

            //SERIALIZER
            var ser = new DataContractSerializer(typeof(List<Person>));

            //WRITE
            FileStream fs = new FileStream("deep.xml", FileMode.Create);
            ser.WriteObject(fs, p);
            fs.Close();

            //READ
            FileStream fs2 = new FileStream("deep.xml", FileMode.Open);
            List<Person> a = new List<Person>();
            a = (List<Person>)ser.ReadObject(fs2);
        }
    }

这是我的问题:


行标记为“有和没有”的序列化似乎可以正常工作,但我无法反序列化,并且在执行此操作时得到“ SerializationException”:

 a = (List<Person>)ser.ReadObject(fs2);

它说错误在第168列中,在这里:

 <Person i:type="Child">

没有那条线,我什至无法序列化。 我得到SerializationException,它说明了意外类型。 此错误来自此行:

ser.WriteObject(fs, p);

我有什么想念的吗? 欢迎对“有和没有它”行的确切含义进行一些解释。 我试图找到答案,但是我对Microsoft网站上的描述不清楚。

我将非常感谢您的帮助。

解决方案:将[KnownType(typeof(Child))]移至Person类。 在多重继承的情况下,可以使用多个KnowType属性。

链接到文档: https : //msdn.microsoft.com/zh-cn/library/ms730167%28v=vs.110%29.aspx

就序列化器而言,要序列化的类型是Person

序列化时, Person没有DataContact属性,因此这是要修复的第一件事。

[DataContract]    
abstract class Person

该列表现在将序列化,但是当您进行反序列化时,会发生类似的问题-反序列化器仅了解Person类型。 文档的相关部分说:

通过首先检查传入的消息以确定消息内容所遵循的数据协定,来选择实例化用于反序列化的类型。 然后,反序列化引擎尝试查找实现与消息内容兼容的数据协定的CLR类型。 反序列化引擎在此过程中允许的候选类型集称为反序列化器的“已知类型”

这就是KnownType属性的来源:

[DataContract]
[KnownType(typeof(Child))]
abstract class Person

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM