序列化期间出现异常 - 不应使用具有数据协定名称的类型
Exception during the serialization - Type with data contract name is not expected
我有这个类:
[DataContract]
class ClassA
{
[DataMember]
public Object Value; // and this can be of ClassB or some primitive type.
...
}
[DataContract]
class ClassB : IEnumerable<KeyValuePair<String, ClassA>>
{
[DataMember]
private Dictionary<String, ClassA> dictionary;
...
}
但在序列化发生时出现此异常:
Type 'MyNamespace.ClassA' with data contract name
'ClassA:http://schemas.datacontract.org/2004/07/MyNamespace' is not
expected. Add any types not known statically to the list of known
types - for example, by using the KnownTypeAttribute attribute or by
adding them to the list of known types passed to
DataContractSerializer.
我觉得我应该使用 KnownType
属性,但我不知道如何使用,因为我没有 IEnumerable<T>
.
有人能帮忙吗?谢谢
尝试以下操作:
[DataContract]
[KnownType(typeof(int))]
// Same way add here all the types that you are using in your class A.
class ClassA
{
[DataMember]
public int Value;
...
}
我终于弄对了。解决方案非常简单,第一个 class 的 Value
是 Object
类型,序列化程序必须知道哪些类型将被装入 Object
.
因此 ClassA
应声明为:
[DataContract]
[KnownType(typeof(ClassA)]
[KnownType(typeof(ClassB)]
class ClassA
{
[DataMember]
public Object Value; // ClassA or ClassB or some primitive type.
...
}
这份文件 here 确实有助于澄清什么是 KnownType
。
我有这个类:
[DataContract]
class ClassA
{
[DataMember]
public Object Value; // and this can be of ClassB or some primitive type.
...
}
[DataContract]
class ClassB : IEnumerable<KeyValuePair<String, ClassA>>
{
[DataMember]
private Dictionary<String, ClassA> dictionary;
...
}
但在序列化发生时出现此异常:
Type 'MyNamespace.ClassA' with data contract name 'ClassA:http://schemas.datacontract.org/2004/07/MyNamespace' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
我觉得我应该使用 KnownType
属性,但我不知道如何使用,因为我没有 IEnumerable<T>
.
有人能帮忙吗?谢谢
尝试以下操作:
[DataContract]
[KnownType(typeof(int))]
// Same way add here all the types that you are using in your class A.
class ClassA
{
[DataMember]
public int Value;
...
}
我终于弄对了。解决方案非常简单,第一个 class 的 Value
是 Object
类型,序列化程序必须知道哪些类型将被装入 Object
.
因此 ClassA
应声明为:
[DataContract]
[KnownType(typeof(ClassA)]
[KnownType(typeof(ClassB)]
class ClassA
{
[DataMember]
public Object Value; // ClassA or ClassB or some primitive type.
...
}
这份文件 here 确实有助于澄清什么是 KnownType
。