XmlSerializer with parameterless constructor with no public properties or fields… Is it possible?

扶醉桌前 提交于 2021-01-28 14:05:37

问题


Having the following class (.Net 3.5):

public class Something
{
    public string Text {get; private set;}

    private Something()
    {
        Text = string.Empty;
    }

    public Something(string text)
    {
        Text = text;
    }
}

This serializes without error but the resulting XML does not include the Text property since it does not have a public setter.

Is there a way (the simpler, the better) to have the XmlSerializer include those properties?


回答1:


XmlSerializer only cares about public read/write members. One option is to implement IXmlSerializable, but that is a lot of work. A more practical option (if available and suitable) may be to use DataContractSerializer:

[DataContract]
public class Something
{
    [DataMember]
    public string Text {get; private set;}

    private Something()
    {
        Text = string.Empty;
    }

    public Something(string text)
    {
        Text = text;
    }
}

This works on both public and private members, but the xml produced is not quite the same, and you can't specify xml attributes.




回答2:


No. XML Serialization will only serialized public read/write fields and properties of objects.




回答3:


Try

[Serializable] public class Something { ... }



来源:https://stackoverflow.com/questions/1065849/xmlserializer-with-parameterless-constructor-with-no-public-properties-or-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!