C#派生类的XML序列化

您好我正在尝试序列化从类派生的对象数组,我使用c#继续遇到相同的错误。 任何帮助深表感谢。

很明显,这个例子已经按照现实世界中这篇文章的目的缩小了。形状将包含大量不同的形状。

Program.cs中

namespace XMLInheritTests { class Program { static void Main(string[] args) { Shape[] a = new Shape[1] { new Square(1) }; FileStream fS = new FileStream("C:\\shape.xml", FileMode.OpenOrCreate); XmlSerializer xS = new XmlSerializer(a.GetType()); Console.WriteLine("writing"); try { xS.Serialize(fS, a); } catch (Exception e) { Console.WriteLine(e.InnerException.ToString()); Console.ReadKey(); } fS.Close(); Console.WriteLine("Fin"); } } } 

Shape.cs

 namespace XMLInheritTests { public abstract class Shape { public Shape() { } public int area; public int edges; } } 

Square.cs

 namespace XMLInheritTests { public class Square : Shape { public int iSize; public Square() { } public Square(int size) { iSize = size; edges = 4; area = size * size; } } } 

错误:System.InvalidOperationException:不期望XMLInheritTests.Square类型。 使用XmlInclude或SoapInclude属性指定静态未知的类型。

在Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterShapeA rray.Write2_Shape(String n,String ns,Shape o,Boolean isNullable,Boolean need Type)

在Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterShapeA rray.Write3_ArrayOfShape(Object o)

非常感谢

 [XmlInclude(typeof(Square))] public abstract class Shape {...} 

(重复所有已知的亚型)

如果类型仅在运行时已知,则可以将它们提供给XmlSerializer构造函数,但是:然后缓存并重用该序列化程序实例非常重要 ; 否则你会出血动态创建的程序集。 当您使用仅接受Type的构造函数时,它会自动执行此操作,但不会对其他重载执行此操作。

解:

 class Program { static void Main(string[] args) { Shape[] a = new Shape[2] { new Square(1), new Triangle() }; FileStream fS = new FileStream("C:\\shape.xml",FileMode.OpenOrCreate); //this could be much cleaner Type[] t = { a[1].GetType(), a[0].GetType() }; XmlSerializer xS = new XmlSerializer(a.GetType(),t); Console.WriteLine("writing"); try { xS.Serialize(fS, a); } catch (Exception e) { Console.WriteLine(e.InnerException.ToString()); Console.ReadKey(); } fS.Close(); Console.WriteLine("Fin"); } } namespace XMLInheritTests { [XmlInclude(typeof(Square))] [XmlInclude(typeof(Triangle))] public abstract class Shape { public Shape() { } public int area; public int edges; } } 

谢谢; 毫无疑问,我很快就会遇到另一个问题:S