类型为T的派生类的序列化

时间:2014-08-07 00:04:00

标签: c# xml serialization

我有以下类需要序列化

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

以下派生类

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; }
}

Whan我尝试序列化Boat类,它说我需要为所有可能的子类添加XmlInclude,但我不能添加SpeedBoat,因为我不知道我将提前有多少类型,例如:

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

有没有办法允许序列化程序使用泛型?

感谢。

1 个答案:

答案 0 :(得分:1)

您可以通过要求T可序列化来解决此问题:

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