在使用 .NET 时,我遇到了一个非常奇怪的问题XmlSerializer。
采取以下示例类:
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由于序列化程序不知道Payment.
1.添加XmlInclude到Payment类定义:
这是不可能的,因为所有类都包含在我无法控制的外部引用中。
XmlSerializer2. 在创建实例时传递派生类型的类型
不工作。
3.定义XmlAttributeOverrides目标属性以覆盖属性的默认序列化(如this SO post中所述)
也不起作用(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不是预期的... ) 被抛出。
任何人都可以对这个主题有所了解吗?如何进一步解决问题?