gpt4 book ai didi

c# - 为什么我不能反序列化 KnownType 的 anyType?

转载 作者:行者123 更新时间:2023-11-30 21:01:57 26 4
gpt4 key购买 nike

我正在尝试在 WCF 外部使用 DataContractSerializer 来序列化一个对象。本例中的对象继承自 CollectionBase 周围的旧通用包装器,例如

[KnownType(typeof(Foo)]
[CollectionDataContract]
class FooCollection : MyCollectionBase<Foo>

[KnownType(typeof(FooCollection)]
[KnownType(typeof(Foo)]
[CollectionDataContract]
class MyCollectionBase<T> : CollectionBase

[DataContract]
class Foo
{
[DataMember]
string Name;
[DataMember]
string Value;
}

序列化后,我得到以下结构:

<FooCollection xmlns="http://schemas.datacontract.org/ ...>
<anyType>
<Name>...</Name>
<Value>...</Value>
</anyType>
</ArrayOfAnyType>

反序列化时出现错误:

System.Runtime.Serialization.SerializationException : Element anyType from namespace http://schemas.datacontract.org/2004/07/MyAssembly cannot have child contents to be deserialized as an object. Please use XmlNode[] to deserialize this pattern of XML.

----> System.Xml.XmlException : End element 'anyType' from namespace 'http://schemas.datacontract.org/2004/07/MyAssembly' expected. Found element 'Name' from namespace 'http://schemas.datacontract.org/2004/07/MyAssembly'. Line 1, position xxx.

谷歌搜索此错误显示许多人更改了他们的继承层次结构以使序列化工作,或者只是列出该方法的问题。我还没有找到任何使用 XmlNode[] 反序列化这种 XML 模式的示例。

所以我的问题是:

  1. 有没有办法让 DataContractSerializer 相信存储在底层 ArrayList 中的类型是 Foo 类型?
  2. 如何实现 XmlNode[] 解决方法?
  3. 是使用不受非通用集合支持的通用集合的唯一解决方案吗?

最佳答案

我找到了问题的原因,但在我原来的问题中没有显示:MyCollectionBase implemented ISerializable。

DataContractSerializer 在使用任何属性之前将使用 ISerializable 实现。它也无法从 ISerializable 中推断出契约(Contract),因此没有针对 anyType 反序列化的解决方法。

这就是 KnownTypeAttribute 不起作用的原因。

关于c# - 为什么我不能反序列化 KnownType 的 anyType?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13755541/

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