class Program { static void Main(string[] args) { BaseElement element = new BillElement(); element.Key = Guid.NewGuid().ToString(); element.Appearance.Caption = "Hello"; element.Left = 100; XmlUtils.XmlSerialize<BaseElement>("C:\\xx.xml", element); XmlUtils.XmlSerialize<BaseElement>("C:\\xx.xml", new BillElement()); Console.ReadKey(); BaseElement element2 = new FieldElement(); element2.Key = Guid.NewGuid().ToString(); element2.Appearance.Caption = "Test2"; element2.Left = 3; List<BaseElement> lstElements = new List<BaseElement>() { element }; XmlUtils.XmlSerialize<List<BaseElement>>("c:\\xx.xml", lstElements); Console.ReadKey(); } }
以上代码 你会发现一个很奇怪的现象,就是第一段直接对派生类序列化不会出错,但是第二段把派生类对象加到集合里进行序列化就会报错:"The type ConsoleApplication4.BillElement was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."
最后查找资料得知解决方式 如下:
http://msdn.microsoft.com/en-us/library/aa302290.aspx