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

本文关键字:序列化 派生 类型 | 更新日期: 2023-09-27 18:16:55

我有以下需要序列化的类

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

当我尝试序列化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; }
}

是否有一种方法允许序列化器通过泛型?

谢谢。

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

您可以通过要求T是可序列化的来解决这个问题:

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