gpt4 book ai didi

c# - 通用类型层次结构的 DataContractSerialization

转载 作者:行者123 更新时间:2023-11-30 16:02:48 24 4
gpt4 key购买 nike

以下程序尝试从层次结构中序列化然后反序列化通用类型的对象,失败并出现代码下方列出的错误。

如何让它发挥作用?

代码:

[DataContract]
[KnownType(nameof(GetKnownTypes))]
public abstract class Base<T>
{
private static Type[] GetKnownTypes()
{
return new[] {typeof(DerivedA<T>)};
}
}


[DataContract]
public class DerivedA<T> : Base<T>
{
[DataMember]
public T Foo { get; set; }
}

class Program
{
private static void Main()
{
// This works fine
var foo = new DerivedA<string> { Foo = "foo" };
var xml = Serialize(foo);
var foo2 = Deserialize<DerivedA<string>>(xml);
Console.WriteLine(foo2.Foo); // foo

// This throws the exception below
// (from serializer.ReadObject() in the Deserialize method)
var foo3 = Deserialize<Base<string>>(xml);
}

private static string Serialize<T>(T o)
{
string result = null;
var serializer = new DataContractSerializer(o.GetType());
using (var stream = new MemoryStream())
{
serializer.WriteObject(stream, o);
stream.Position = 0;

var reader = new StreamReader(stream);
result = reader.ReadToEnd();
}
return result;
}

private static T Deserialize<T>(string xml)
{
var result = default(T);
var serializer = new DataContractSerializer(typeof(T));
using (var stream = new MemoryStream())
{
var writer = new StreamWriter(stream);
writer.Write(xml);
writer.Flush();
stream.Position = 0;

result = (T)serializer.ReadObject(stream);
}
return result;
}
}

异常:

Unhandled Exception: System.Runtime.Serialization.SerializationException: Error in line 1 position 139. Expecting element 'BaseOfstring' from namespace 'http://schemas.datacontract.org/2004/07/ConsoleApplication7'.. Encountered 'Element'  with name 'DerivedAOfstring', namespace 'http://schemas.datacontract.org/2004/07/ConsoleApplication7'.
at System.Runtime.Serialization.DataContractSerializer.InternalReadObject(XmlReaderDelegator xmlReader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.XmlObjectSerializer.ReadObject(XmlDictionaryReader reader)
at System.Runtime.Serialization.XmlObjectSerializer.ReadObject(Stream stream)
at ConsoleApplication7.Program.Deserialize[T](String xml) in c:\users\tly01\documents\visual studio 2015\Projects\ConsoleApplication7\ConsoleApplication7\Program.cs:line 65

消息中最有趣的部分非常清楚出了什么问题:

Expecting element 'BaseOfstring' from namespace . Encountered 'Element' with name 'DerivedAOfstring', namespace .

果然,上面main方法中的xml是这样的(加了空格):

<DerivedAOfstring
xmlns="http://schemas.datacontract.org/2004/07/ConsoleApplication7"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Foo>foo</Foo>
</DerivedAOfstring>

我意识到我必须以某种方式让序列化程序知道我的类型层次结构,但我已经尝试了上面列表中 KnownType 属性的许多不同变体,但没有一个有卓有成效。使这项工作正常进行的正确方法是什么?

最佳答案

您需要做的是始终使用 DataContractSerializer 序列化和反序列化您的派生类型。 constructed using identical Type arguments .您正在尝试使用 DerivedA<T>用于序列化和 Base<T>用于反序列化。这种不一致会导致您看到的问题。

发生这种情况的原因如下。通常,有两种常规方法可以将多态类型序列化为 XML:

事实DataContractSerializer使用第二种机制是导致您的问题的原因。当您序列化派生类的实例时,派生类协定名称将作为根元素名称发出。但是,当您将派生类的实例作为其基类的实例 序列化时,基类协定名称将与附加的 xsi:type 一起使用。 .要看到这一点,请按如下方式重构您的代码:

    private static string Serialize<T>(T o)
{
return Serialize(o, null);
}

private static string Serialize<T>(T o, DataContractSerializer serializer)
{
string result = null;
serializer = serializer ?? new DataContractSerializer(o.GetType());
using (var stream = new MemoryStream())
{
serializer.WriteObject(stream, o);
stream.Position = 0;

var reader = new StreamReader(stream);
result = reader.ReadToEnd();
}
return result;
}

现在如果你这样做:

var xml = Serialize(foo);
Debug.WriteLine(xml);

你会看到

<DerivedAOfstring 
xmlns="http://schemas.datacontract.org/2004/07/Question37284138" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Foo>foo</Foo>
</DerivedAOfstring>

但如果你这样做

var baseXml = Serialize(foo, new DataContractSerializer(typeof(Base<string>)));
Debug.WriteLine(baseXml);

你会看到:

<BaseOfstring i:type="DerivedAOfstring"
xmlns="http://schemas.datacontract.org/2004/07/Question37284138" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Foo>foo</Foo>
</BaseOfstring>

注意到区别了吗?这意味着前者不能使用 DataContractSerializer(typeof(Base<string>)) 反序列化。 .但是如果你序列化使用 DataContractSerializer(typeof(Base<string>))然后反序列化将起作用 - 并正确构造 DerivedA<string> 的实例感谢 xsi:type 的存在属性。

关于c# - 通用类型层次结构的 DataContractSerialization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37284138/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com