使用 DataContractSerializer 忽略嵌套类型
Ignore Nested Types with DataContractSerializer
我在 C# 中有一个 class,我正尝试使用 DataContractSerializer 对其进行序列化。它看起来像这样:
namespace Foo
{
[DataContract(Name = "Bar")]
class Bar
{
class A
{
public A(object a, object b, object c)
{
d = a;
e = b;
f = c;
}
public object d;
public object e;
public object f;
}
[DataMember]
private ArrayList lst = new ArrayList();
...
}
}
当我尝试序列化此 class 时,出现错误:
"System.Runtime.Serialization.SerializationException: Type 'Foo.Bar+A' with data contract name '...' is not expected. Consider using a DataContractResolver if you are using DataContractSerializer or add any types not known statically to the list of known types."
我想做的是忽略A。它只是一个类型的定义。 None 我尝试序列化的 DataMembers 是 A 类型。
编辑:这是序列化代码。
public void Serialize()
{
var writer = new FileStream("testoutput.xml", FileMode.Create);
var serializer = new DataContractSerializer(typeof(Bar));
serializer.WriteObject(writer, this);
writer.Close();
}
在 serializer.WriteObject.
上抛出异常
在仔细研究之后,我能够像这样修复它:
[KnownType(typeof(A))]
[DataContractAttribute]
class A
{
public A(object a, object b, object c)
{
d = a;
e = b;
f = c;
}
[DataMember]
public object d;
[DataMember]
public object e;
[DataMember]
public object f;
}
我认为其中一个数组列表实际上持有 As。这个 class 很大,所以我可能错过了它。
我在 C# 中有一个 class,我正尝试使用 DataContractSerializer 对其进行序列化。它看起来像这样:
namespace Foo
{
[DataContract(Name = "Bar")]
class Bar
{
class A
{
public A(object a, object b, object c)
{
d = a;
e = b;
f = c;
}
public object d;
public object e;
public object f;
}
[DataMember]
private ArrayList lst = new ArrayList();
...
}
}
当我尝试序列化此 class 时,出现错误:
"System.Runtime.Serialization.SerializationException: Type 'Foo.Bar+A' with data contract name '...' is not expected. Consider using a DataContractResolver if you are using DataContractSerializer or add any types not known statically to the list of known types."
我想做的是忽略A。它只是一个类型的定义。 None 我尝试序列化的 DataMembers 是 A 类型。
编辑:这是序列化代码。
public void Serialize()
{
var writer = new FileStream("testoutput.xml", FileMode.Create);
var serializer = new DataContractSerializer(typeof(Bar));
serializer.WriteObject(writer, this);
writer.Close();
}
在 serializer.WriteObject.
上抛出异常在仔细研究之后,我能够像这样修复它:
[KnownType(typeof(A))]
[DataContractAttribute]
class A
{
public A(object a, object b, object c)
{
d = a;
e = b;
f = c;
}
[DataMember]
public object d;
[DataMember]
public object e;
[DataMember]
public object f;
}
我认为其中一个数组列表实际上持有 As。这个 class 很大,所以我可能错过了它。