I'm trying to serialize an array of Test
objects that contains some TestC开发者_运维技巧hild
objects.
public class Test
{
public string SomeProperty { get; set; }
}
public class TestChild : Test
{
public string SomeOtherProperty { get; set; }
}
class Program
{
static void Main()
{
Test[] testArray = new[]
{
new TestChild { SomeProperty = "test1", SomeOtherProperty = "test2" },
new TestChild { SomeProperty = "test3", SomeOtherProperty = "test4" },
new TestChild { SomeProperty = "test5", SomeOtherProperty = "test6" },
};
XmlSerializer xs = new XmlSerializer(typeof(Test));
using (XmlWriter writer = XmlWriter.Create("test.xml"))
xs.Serialize(writer, testArray);
}
}
I get and InvalidOperationException that says TestChild cannot be converted to Test.
This makes sense but is there a way to do it anyway?
The simplest way is to annotate the class so that the serializer anticipates the subclass:
[XmlInclude(typeof(TestChild))]
public class Test
{
public string SomeProperty { get; set; }
}
Otherwise (if using the more complex constructors for XmlSerializer
) you need to be very careful to cache and re-use the serializer instance - otherwise it will haemorrhage memory (it creates an assembly each time that cannot be garbage-collected; the simplest constructor taking just a Type
handles this caching for you).
You could specify known types by using the proper constructor, also you are serializing a test array Test[]
and not Test
, hence the first argument of the constructor should be typeof(Test[])
:
var xs = new XmlSerializer(typeof(Test[]), new Type[] { typeof(TestChild) });
精彩评论