gpt4 book ai didi

c# - 为什么 XML-Serializable 类需要无参数构造函数

转载 作者:IT王子 更新时间:2023-10-29 03:30:39 26 4
gpt4 key购买 nike

我正在编写代码来进行 Xml 序列化。具有以下功能。

public static string SerializeToXml(object obj)
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
using (StringWriter writer = new StringWriter())
{
serializer.Serialize(writer, obj);
return writer.ToString();
}
}

如果参数是没有无参数构造函数的类的实例,则会抛出异常。

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序列化成功?

编辑:感谢 cfeduke 的回答。无参数构造函数可以是私有(private)的或内部的。

最佳答案

在对象的反序列化过程中,负责反序列化对象的类创建序列化类的实例,然后仅在获取要填充的实例后才继续填充序列化的字段和属性。

如果需要,您可以将构造函数设为 privateinternal,只要它是无参数的即可。

关于c# - 为什么 XML-Serializable 类需要无参数构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/267724/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com