3

我有一个基类的对象数组MyBase。其中一些对象是派生类的实例,因此当我尝试使用System.Xml.Serialization.XmlSerializer它序列化此数组时,它会因对派生类的抱怨而失败:System.InvalidOperationException: DerivedClass 类型不是预期的。使用 XmlInclude 或 SoapInclude 属性指定静态未知的类型。

我不想序列化派生类,我绝对不想放入[XmlIgnore()]派生类(或[XmlInclude()]基类中,就此而言)!

有没有办法告诉XmlSerializer只为这样的成员序列化基础

[XmlElement("Items")]
public MyBase[] Items
{
    get
    {
        return items.ToArray();
    }
    set 
    {
        items = new HashSet<MyBase>(value);
    }
}
4

1 回答 1

1

您可以对项目集合进行 Linq 查询,过滤类型:

[XmlElement("Items")]
public MyBase[] Items
{
    get
    {
        return items.Where(item => item.GetType() == typeof(MyBase)).ToArray();
    }
    set 
    {
        items = new HashSet<MyBase>(value);
    }
}
于 2012-04-12T20:41:25.670 回答