为什么XML序列化类需要一个参数的构造函数 [英] Why XML-Serializable class need a parameterless constructor

查看:285
本文介绍了为什么XML序列化类需要一个参数的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写code做的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(类型   类型的MemberInfo源码,E,布尔   directReference,布尔throwOnError)   在   System.Xml.Serialization.ModelScope.GetTypeModel(类型   型,布尔直接参考)在   System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(类型   类型,XmlRootAttribute根,字符串   DefaultNamespace的)在   System.Xml.Serialization.XmlSerializer..ctor(类型   类型,字符串defaultName中空间)在   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.

您可以让您的构造函数私人内部如果你想要,就只要它的参数的。

You can make your constructor private or internal if you want, just so long as its parameterless.

这篇关于为什么XML序列化类需要一个参数的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆