DataContractSerializer、KnownType 和继承
我读过很多关于已知类型的文章,我相信我的例子应该有效。 但事实并非如此。 我在反序列化时遇到以下异常,不明白为什么:
第 1 行位置 2 中出现错误。期望来自命名空间 'http://schemas.datacontract.org/2004/07/ConsoleApplication2'.. 遇到名称为“C”、命名空间为“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);
}
}
}
我缺少什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
改变创建序列化器的方式。 使用:
代替a.GetType();
有用。 生成的 Xml 是不同的 - 是这样的:
现在是:
Change the way you create serializer. Use:
instead of a.GetType();
It works. The Xml that is generated is different - was something like this:
and now is: