ผมเคยมีปัญหาแปลกมากเมื่อทำงานกับ XmlSerializer.NET
เรียนตามตัวอย่างต่อไปนี้:
public class Order
{
public PaymentCollection Payments { get; set; }
//everything else is serializable (including other collections of non-abstract types)
}
public class PaymentCollection : Collection<Payment>
{
}
public abstract class Payment
{
//abstract methods
}
public class BankPayment : Payment
{
//method implementations
}
AFAIK มีสามวิธีในการแก้ปัญหาInvalidOperationExceptionที่เกิดจาก serializer ไม่รู้เกี่ยวกับประเภทที่ได้รับของPayment.
1. การเพิ่มXmlIncludeกับPaymentการกำหนดระดับ:
สิ่งนี้เป็นไปไม่ได้เนื่องจากคลาสทั้งหมดถูกรวมเป็นข้อมูลอ้างอิงภายนอกซึ่งฉันไม่สามารถควบคุมได้
2. ส่งผ่านประเภทที่ได้รับมาระหว่างการสร้างXmlSerializerอินสแตนซ์
ไม่ทำงาน
3. การXmlAttributeOverridesกำหนดคุณสมบัติเป้าหมายเพื่อแทนที่การทำให้เป็นอนุกรมเริ่มต้นของคุณสมบัติ (ตามที่อธิบายไว้ในโพสต์ SO นี้ )
ยังไม่ทำงาน (การXmlAttributeOverridesเริ่มต้นตามมา)
Type bankPayment = typeof(BankPayment);
XmlAttributes attributes = new XmlAttributes();
attributes.XmlElements.Add(new XmlElementAttribute(bankPayment.Name, bankPayment));
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
overrides.Add(typeof(Order), "Payments", attributes);
XmlSerializerจากนั้นจะใช้ตัวสร้างที่เหมาะสม
หมายเหตุ: โดยไม่ทำงานฉันหมายถึงInvalidOperationException( BankPaymentไม่คาดว่า ... ) ถูกโยน
ใครช่วยให้ความกระจ่างเกี่ยวกับเรื่องนี้ได้บ้าง? เราจะดำเนินการแก้ไขปัญหาต่อไปอย่างไร