使用XmlInclude或SoapInclude属性来指定不属于已知的静态类型不属于、静态、属性、类型

由网友(梦醒伤人心)分享简介:与.NET的的XmlSerializer 工作时,我有一个很奇怪的问题。 I've got a very strange problem when working with .NET's XmlSerializer. 看看下面的例子类:public class Order {public PaymentColl...

与.NET的的XmlSerializer 工作时,我有一个很奇怪的问题。

I've got a very strange problem when working with .NET's 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异常就是造成串行不知道有关的派生类型付款

AFAIK, there are three different methods to solve the InvalidOperationException that's caused by the serializer not knowing about the derived types of Payment.

1。添加 XmlInclude 付款类的定义:

1. Adding XmlInclude to the Payment class definition:

这是不可能的,因为所有的类被列为外部引用过,我无法控制的。

This is not possible due to all classes being included as external references over which I have no control of.

2。创建的XmlSerializer 实例期间过派生类型'类型

2. Passing the derived types' types during creation of the XmlSerializer instance

不能正常工作。

3。定义 XmlAttributeOverrides 中以覆盖该属性的默认序列化(如这个SO帖子)

3. Defining XmlAttributeOverrides for the target property in order to override the property's default serialization (as explained in this SO post)

也不起作用( XmlAttributeOverrides 初始化如下)。

Also doesn't work (XmlAttributeOverrides initialization follows).

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 的构造函数将被使用。

The appropriate XmlSerializer constructor would then be used.

注:按不起作用的我的意思是 InvalidOperationException异常 BankPayment 是没有预料到...... 的)被抛出。

NOTE: by doesn't work I mean the InvalidOperationException (BankPayment was not expected...) is thrown.

任何人都可以阐明这个问题一些启示?如何将一去,进一步调试问题?

Can anyone shed some light on the subject? How would one go about and debug the issue further?

推荐答案

刚刚解决了这个问题。周围挖了一段时间后,我发现this SO帖子覆盖完全相同的情况。这让我在正确的轨道上。

Just solved the issue. After digging around for a while longer, I found this SO post which covers the exact same situation. It got me in the right track.

基本上,的XmlSerializer 需要知道默认的命名空间如果派生类都包含作为额外的类型。确切的原因,这种情况发生仍是个未知数,但是,尽管如此,序列化的工作了。

Basically, the XmlSerializer needs to know the default namespace if derived classes are included as extra types. The exact reason why this has to happen is still unknown but, still, serialization is working now.

阅读全文

相关推荐

最新文章