简体   繁体   中英

Serializing derived class doesn't include base class' fields

Suppose I have the following 2 classes in my C# program:

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

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

And, in my program I am trying to serialize a List<Derived> to XML via:

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

But it's not pulling in the Base fields - str1 , str2 and str3 in the output.

I'm fairly new to this and hoping this should be easy / require just an addition input to the serializer (I tried adding in the extra Base type, but still no luck), but I'm just not able to figure it out.

Any help would be really appreciated!!!

Thanks!

[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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM