I have 2 classes
[DataContract, KnownType(typeof(B))]
public class A
{
[DataMember]
public string prop1 { get; set; }
[DataMember]
public string prop2 { get; set; }
[DataMember]
public string prop3 { get; set; }
}
[DataContract]
public class B : A
{
[DataMember]
public string prop4 { get; set; }
}
and the following method:
List<B> BList = new List<B>();
BList = new List<B>() { new B() { prop1 = "1", prop2 = "2", prop3 = "3", prop4 = "4" } };
List<A> AList = BList.Cast<A>().ToList();
DataContractSerializer ser = new DataContractSerializer(typeof(List<A>));
FileStream fs = new FileStream(@"C:\temp\AResult.xml", FileMode.Create);
using (fs)
{
ser.WriteObject(fs, AList);
}
which writes this to the outcoming XML file:
<ArrayOfProgram.A xmlns="http://schemas.datacontract.org/2004/07/foo" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Program.A i:type="Program.B">
<prop1>1</prop1>
<prop2>2</prop2>
<prop3>3</prop3>
<prop4>4</prop4>
</Program.A></ArrayOfProgram.A>
How could it happen, that prop4
is within the result and how can I avoid this? prop4
is not part of List<A>
which is being serialized.
prop4
is not a part of classA
, butList<A>
can store objects of typeB
, so when you serialize the elements ofList<A>
then the serializer will take the actual types stored (not just the element type of the list). – Siliculose