DataContractSerializer, KnownType and inheritance

一世执手 提交于 2019-12-21 01:57:10

问题


I've read many articles about known types and i belive my example should work. But it doesn't. I'm getting the following exception on deserialization and don't understand why:

Error in line 1 position 2. Expecting element 'A' from namespace 'http://schemas.datacontract.org/2004/07/ConsoleApplication2'.. Encountered 'Element' with name 'C', namespace 'http://schemas.datacontract.org/2004/07/ConsoleApplication2'.

using System;
using System.Runtime.Serialization;
using System.Xml;
using System.IO;

namespace ConsoleApplication2
{
    [DataContract][KnownType(typeof(C))]class A { }
    [DataContract]class C : A { }

    class Program
    {
        static void Main(string[] args)
        {
            A a = new C();
            string data;

            var serializer = new DataContractSerializer(a.GetType());
            using (var sw = new StringWriter())
            {
                using (var xw = new XmlTextWriter(sw))
                    serializer.WriteObject(xw, a);
                data = sw.ToString();
            }

            serializer = new DataContractSerializer(typeof(A));
            using (var sr = new StringReader(data))
            using (var xr = new XmlTextReader(sr))
                a = (A)serializer.ReadObject(xr);
        }
    }
}

What am i missing?


回答1:


Change the way you create serializer. Use:

var serializer = new DataContractSerializer(typeof(A));

instead of a.GetType();

It works. The Xml that is generated is different - was something like this:

<C> ...

and now is:

<A i:type="C"> ...


来源:https://stackoverflow.com/questions/1177555/datacontractserializer-knowntype-and-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!