17

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

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

程序.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");
        }
    }
}

形状.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 array.Write3_ArrayOfShape(Object o)

非常感谢

4

2 回答 2

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

(对所有已知的亚型重复)

如果类型仅在运行时已知,您可以将它们提供给XmlSerializer构造函数,但是:缓存和重用该序列化程序实例很重要;否则,您将大量使用动态创建的程序集。当您使用仅采用 a 的构造函数时,它会自动执行此操作Type,但不适用于其他重载。

于 2010-07-24T19:15:50.917 回答
3

解决方案:

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

于 2010-07-24T19:36:45.103 回答