I am trying to serialize a list of descendants. This is what I have now, that works fine:
class Animal {}
class Zebra:Animal{}
class Hippo:Animal{}
[XmlRootAttribute("Zoo")]
class Zoo
{
[XmlArrayItem(typeof(Zebra))]
[XmlArrayItem(typeof(Hippo))]
public List<Animal> Actions
{ set; get; }
}
This works fine and I can serialize both Animal
s. I wonder If it is possible to create an Attribute
class where I can pass the list of animals (instances), and will create for me the XmlArrayItem
s attributes.
In general, I am looking for a way to avoid specifying the descendants of Animal
everytime I create a new one. I want all descendants of Animal
to be serialized, whatever their type.
You can get a list of derived types within an assembly like so:
public IEnumerable<Type> GetAllTypesDerivedFrom(Type type)
{
var types = Assembly.GetAssembly(type).GetTypes();
return types.Where(t => t.IsSubclassOf(type));
}
Perhaps you can cycle through a foreach loop on the GetAllTypesDerivedFrom method above, and then fit it into a solution similar to the MSDN example for XmlArrayItems.
NOTE: If you need to get all derived types for an interface, you'll instead need to use the following (would work with both interfaces and classes):
return types.Where(type.IsAssignableFrom).Where(t => t != type);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With