使用XmlInclude或SoapInclude属性指定静态未知的types
使用.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,有三种不同的方法来解决由于序列化程序不知道派生types的Payment而导致的InvalidOperationException 。 
  1.将XmlInclude添加到Payment类定义中: 
这是不可能的,因为所有的类都被包含为我无法控制的外部引用。
  2.在创buildXmlSerializer实例期间传递派生types的types 
不起作用。
  3.为目标属性定义XmlAttributeOverrides以覆盖该属性的默认序列化(如本文所述) 
 也不起作用( 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不预期… )被抛出。 
任何人都可以谈一谈这个问题? 如何进一步解决问题呢?
这对我工作:
 [XmlInclude(typeof(BankPayment))] [Serializable] public Payment { } [Serializable] public class BankPayment : Payment {} [Serializable] public class Payments : List<Payment>{} XmlSerializer serializer = new XmlSerializer(typeof(Payments), new Type[]{typeof(Payment)}); 
刚刚解决了这个问题。 经过一段时间的挖掘后,我发现这个SOpost涵盖了完全相同的情况。 这让我走上了正轨。
 基本上, XmlSerializer需要知道默认命名空间, 如果派生类被包含为额外的types。 这种事情发生的确切原因还不得而知,但现在序列化仍在进行中。