Reputation: 1050
I'm working with serialization in C# right now and I've run into a problem that I can't seem to find an answer to. So I have a serializable class with a list of another serializable class as a property. I needed one of the items in the list to have a distinct property in it so I made a subclass and added it to the list as before. That's when the serialization issues popped up so I can only imagine that lists can't be serialized with inherited classes in them, but why? And how would a similar end be met? Anyways, here's an example of what I'm trying to accomplish:
[Serializable]
public class aList
{
[XmlElement]public List<b> list = new List<b>();
public aList()
{
list.Add(new b());
list.Add(new b());
list.Add(new c());
}
}
[Serializable]
public class b
{
[XmlElement]public int prop1;
[XmlElement]public string prop2;
public b()
{
prop1 = 0;
prop2 = String.Empty;
}
}
[Serializable]
public class c : b
{
[XmlElement]public bool prop3;
public c() : base()
{
prop3 = false;
}
}
Upvotes: 2
Views: 1028
Reputation: 1322
XmlInclude
attributes. They're kind of...janky. Basically, you give attributes to your classes that give hints to the serializer about your inheritance.
Specifically:
[Serializable]
[XmlInclude(typeof(c))]
public class b
{
[XmlElement]
public int prop1;
[XmlElement]
public string prop2;
public b()
{
prop1 = 0;
prop2 = String.Empty;
}
}
Upvotes: 4
Reputation: 69
May be try using an array instead of a list. An array is serializable if the element it's holding is serializable.
Upvotes: -2