Serialization of derived classes with type T

I have the following class that I need to serialize

public class Boat
{
   public string Brand { get; set; }
   public string Model { get; set; }
}

And the following derived classes

public class WindBoat : Boat
{
    public int MaxSpeed { get; set }
}

public class SpeedBoat<T> : Boat
{
    public int MaxSpeed { get; set; }
    public Engine<T> Engine { get; set; }
}

What I'm trying to serialize the Boat class, it says that I need to add XmlInclude for all possible subclasses, but I cannot add SpeedBoat, because I do not know how many types I will have in advance, for example:

[XmlInclude(typeof(WindBoat)]
[XmlInclude(typeof(SpeedBoat<T>)] <-- Not acceptable
public class Boat
{
   public string Brand { get; set; }
   public string Model { get; set; }
}

Is there any way to allow serializer to pass with generics?

Thank.

+4
source share
1 answer

You can get around this problem by requiring serialization of T:

public class SpeedBoat<T> : Boat where T: IXmlSerializable
{
    public int MaxSpeed { get; set; }
    public Engine<T> Engine { get; set; }
}
+1
source

All Articles