[英]Ignore Nested Types with DataContractSerializer
I have a class in C# that I am trying to serialize using a DataContractSerializer. 我在C#中有一个要尝试使用DataContractSerializer进行序列化的类。 It looks something like this: 看起来像这样:
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();
...
}
}
When I try to serialize this class, I get an error: 当我尝试序列化此类时,出现错误:
"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." “ System.Runtime.Serialization.SerializationException:不应使用数据协定名称为'...'的类型'Foo.Bar + A'。如果您使用的是DataContractSerializer,请考虑使用DataContractResolver或将静态未知的任何类型添加到列表中已知类型。”
What I want to do is ignore A. It is just the definition of a type. 我想做的是忽略A。它只是类型的定义。 None of the DataMembers I am trying to serialize are of type A. 我要序列化的DataMember都不是A类型的。
Edit: This is the serialization code. 编辑:这是序列化代码。
public void Serialize()
{
var writer = new FileStream("testoutput.xml", FileMode.Create);
var serializer = new DataContractSerializer(typeof(Bar));
serializer.WriteObject(writer, this);
writer.Close();
}
The exception is thrown on serializer.WriteObject. 在serializer.WriteObject上引发异常。
After poking around a little bit more, I was able to fix it like this: 经过一番戳后,我能够像这样修复它:
[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;
}
I think that one of the arraylists was actually holding As. 我认为其中一个arraylist实际上持有As。 This class is massive, so I probably just missed it. 这堂课很大,所以我可能只是错过了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.