tôi có 2 lớpđầu ra không hợp lệ với lớp kế thừa
[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; }
}
và phương pháp sau:
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);
}
mà viết này đến tập tin outcoming XML:
<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>
Làm thế nào có thể xảy ra, rằng prop4
nằm trong kết quả và làm cách nào tôi có thể void này? prop4
không phải là một phần của List<A>
đang được đăng.
'prop4' không phải là một phần của lớp' A', nhưng 'Danh sách 'có thể lưu trữ các đối tượng kiểu' b', vì vậy khi bạn serialize các yếu tố của 'List ' sau đó bộ nối tiếp sẽ lấy các kiểu thực được lưu trữ (không chỉ loại phần tử của danh sách). – Enigmativity