C# XML serialization of derived classes

前端 未结 2 878
后悔当初
后悔当初 2020-12-03 16:58

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 th

相关标签:
2条回答
  • 2020-12-03 17:37

    Solution:

    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;
        }
    }
    

    Thanks; I no doubt will have another problem very soon :S

    0 讨论(0)
  • 2020-12-03 17:51
    [XmlInclude(typeof(Square))]
    public abstract class Shape {...}
    

    (repeat for all known subtypes)

    If the types are only known at runtime, you can supply them to the XmlSerializer constructor, but: then it is important to cache and reuse that serializer instance; otherwise you will haemorrhage dynamically created assemblies. It does this automatically when you use the constructor that just takes a Type, but not for the other overloads.

    0 讨论(0)
提交回复
热议问题