派生类的C#XML序列化 [英] C# XML serialization of derived classes
问题描述
您好我试图序列化一个对象的数组,这是从一个类派生的,我使用c#继续碰到相同的错误。任何帮助是非常感激。
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
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
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属性指定静态未知的类型。
Error: System.InvalidOperationException: The type XMLInheritTests.Square was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.
在Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterShapeA
rray.Write2_Shape(String n ,String ns,Shape o,Boolean isNullable,Boolean need
类型)
at 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)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterShapeA rray.Write3_ArrayOfShape(Object o)
很感谢
推荐答案
[XmlInclude(typeof(Square))]
public abstract class Shape {...}
b $ b
(对所有已知子类型重复)
(repeat for all known subtypes)
如果类型只在运行时已知,可以将它们提供给 XmlSerializer
构造函数,但是:重要用于缓存和重用该序列化实例;否则你会出现动态创建的程序集。当你使用只需要一个 Type
的构造函数,而不是其他重载的构造函数时,它会自动执行。
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.
这篇关于派生类的C#XML序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!