【问题标题】:Serializing derived class doesn't include base class' fields序列化派生类不包括基类的字段
【发布时间】:2015-07-24 17:51:00
【问题描述】:

假设我的 C# 程序中有以下 2 个类:

[Serializable]
public class Base
{
    public string str1;
    public string str2;
    public string str3;
}

[Serializable]
public class  Derived : Base
{
    public string str4;
    public string str5;
}

而且,在我的程序中,我试图通过以下方式将List<Derived> 序列化为 XML:

List<Derived> ToSerialize;
string path;
...
var ser = new XmlSerializer(typeof(List<Derived>));
using (var fs = new FileStream(path, FileMode.Create))
{
    ser.Serialize(fs, ToSerialize);
}

但它没有拉入 Base 字段 - str1str2str3 在输出中。

我对此很陌生,希望这应该很容易/只需要向序列化程序添加一个额外的输入(我尝试添加额外的 Base 类型,但仍然没有运气),但我无法弄清楚出来吧。

任何帮助将不胜感激!!!

谢谢!

【问题讨论】:

标签: c# xml inheritance serialization


【解决方案1】:
[XmlInclude(typeof(Derived))]
[Serializable]
public class Base
{
    public string str1;
    public string str2;
    public string str3;
}

[Serializable]
public class  Derived : Base
{
    public string str4;
    public string str5;
}

....

var ser = new XmlSerializer(typeof(Base));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    相关资源
    最近更新 更多