【发布时间】:2010-07-25 03:36:45
【问题描述】:
您好,我正在尝试序列化从类派生的对象数组,但我一直使用 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 类型)
在 Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterShapeA array.Write3_ArrayOfShape(Object o)
非常感谢
【问题讨论】:
-
顺便说一句,公共字段通常要避免;
public int Size {get;set;}会更好。 -
您可以也将边缘和大小设置为虚拟
get属性,这样您就不需要存储它们了。跨度>