C# XML serialization of derived classes

111*_*111 15 c# xml class derived

Hi I am trying to serialize an array of objects which are derived from a class and I keep hitting the same error using c#. Any help is much appreciated.

obviously this example has been scaled down for the purpose of this post in the real world Shape would contain a plethora of different shapes.

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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Shape.cs

namespace XMLInheritTests
{
    public abstract class Shape
    {
        public Shape() { }
        public int area;
        public int edges;
    }
}
Run Code Online (Sandbox Code Playgroud)

Square.cs

namespace XMLInheritTests
{
    public  class  Square : Shape
    {
        public int iSize;
        public Square() { }

        public Square(int size)
        {
            iSize = size;
            edges = 4;
            area = size * size;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Error: System.InvalidOperationException: The type XMLInheritTests.Square was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.

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

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

非常感谢

Mar*_*ell 23

[XmlInclude(typeof(Square))]
public abstract class Shape {...}
Run Code Online (Sandbox Code Playgroud)

(重复所有已知的亚型)

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