C# 类型为T的派生类的序列化
我需要序列化以下类C# 类型为T的派生类的序列化,c#,xml,serialization,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
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; }
}
公共级风艇:风艇
{
public int MaxSpeed{get;set}
}
公营快艇
{
public int MaxSpeed{get;set;}
公共引擎引擎{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; }
}
[xmlclude(风艇类型)]
[xmlclude(typeof(SpeedBoat)]您可以通过要求T可序列化来解决此问题:
public class SpeedBoat<T> : Boat where T: IXmlSerializable
{
public int MaxSpeed { get; set; }
public Engine<T> Engine { get; set; }
}
公共级快艇:T:IXmlSerializable的快艇
{
public int MaxSpeed{get;set;}
公共引擎引擎{get;set;}
}
您是否尝试过typeof(SpeedBoat)
?是..编译但在运行时触发异常…它需要一个类型。。。