加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 类型为T的派生类的序列化

发布时间:2020-12-15 22:06:56 所属栏目:百科 来源:网络整理
导读:我有以下类需要序列化 public class Boat{ public string Brand { get; set; } public string Model { get; set; }} 以及派生类 public class WindBoat : Boat{ public int MaxSpeed { get; set }}public class SpeedBoatT : Boat{ public int MaxSpeed { ge
我有以下类需要序列化

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

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

谢谢.

解决方法

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读