为什么 XML-Serializable 类需要无参数构造函数 [英] Why XML-Serializable class need a parameterless constructor
问题描述
我正在编写代码来进行 Xml 序列化.具有以下功能.
I'm writing code to do Xml serialization. With below function.
public static string SerializeToXml(object obj)
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
using (StringWriter writer = new StringWriter())
{
serializer.Serialize(writer, obj);
return writer.ToString();
}
}
如果参数是没有无参数构造函数的类的实例,则会抛出异常.
If the argument is a instance of class without parameterless constructor, it will throw a exception.
未处理的异常:System.InvalidOperationException:CSharpConsole.Foo 不能被序列化因为它没有无参数构造函数.在System.Xml.Serialization.TypeDesc.CheckSupported()在System.Xml.Serialization.TypeScope.GetTypeDesc(Type类型、成员信息源 e、布尔值directReference, Boolean throwOnError)在System.Xml.Serialization.ModelScope.GetTypeModel(类型类型,布尔直接引用)在System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(类型类型,XmlRootAttribute 根,字符串默认命名空间)在System.Xml.Serialization.XmlSerializer..ctor(类型类型,字符串默认名称空间)在System.Xml.Serialization.XmlSerializer..ctor(类型类型)
Unhandled Exception: System.InvalidOperationException: CSharpConsole.Foo cannot be serialized because it does not have a parameterless constructor. at System.Xml.Serialization.TypeDesc.CheckSupported() at System.Xml.Serialization.TypeScope.GetTypeDesc(Type type, MemberInfo sourc e, Boolean directReference, Boolean throwOnError) at System.Xml.Serialization.ModelScope.GetTypeModel(Type type, Boolean direct Reference) at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type type , XmlRootAttribute root, String defaultNamespace) at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultName space) at System.Xml.Serialization.XmlSerializer..ctor(Type type)
为什么必须要有一个无参数的构造函数才能让xml序列化成功?
Why must there be a parameterless constructor in order to allow xml serialization to succeed?
感谢 cfeduke 的回答.无参数构造函数可以是私有的,也可以是内部的.
thanks for cfeduke's answer. The parameterless constructor can be private or internal.
推荐答案
在对象的反序列化过程中,负责反序列化对象的类会创建序列化类的实例,然后继续填充序列化的字段和属性仅在获取要填充的实例之后.
During an object's de-serialization, the class responsible for de-serializing an object creates an instance of the serialized class and then proceeds to populate the serialized fields and properties only after acquiring an instance to populate.
如果需要,您可以将构造函数设为 private
或 internal
,只要它是无参数的即可.
You can make your constructor private
or internal
if you want, just so long as it's parameterless.
这篇关于为什么 XML-Serializable 类需要无参数构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!