简体   繁体   中英

How to tell System.Xml.Serialization.XmlSerializer to only serialize base class?

I have an array of objects of my base class MyBase . Some of these objects are instances of derived classes so when I try to serialize this array using System.Xml.Serialization.XmlSerializer it fails with complaints about the derived classes: System.InvalidOperationException: The type DerivedClass was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.

I don't want to serialize the derived classes, and I definitely don't want to put [XmlIgnore()] in the derived classes (or [XmlInclude()] in the base class, for that matter)!

Is there a way to tell XmlSerializer to only serialize the base for a member such as this one?

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

You could do a Linq query on the items collection, filtering on type:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM