XmlSerializer忽略公共字段?

wfo*_*orl 4 c# ignore xmlserializer

我正在使用一些现有的代码,定义如下.

class Example
{
    public float x_field;
    public float x_property
    {
        get { return x_field; }
        set { x_field = value; }
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么它这样定义我不知道,但我无法改变它的实现.问题是,当我序列化它时,我显然在xml输出中得到了两个值.如果我无法修改'Example'类,怎么能阻止这种情况发生?

我希望Serializer只输出公共属性而不是公共字段.

Jam*_*mes 6

您可以使用XmlSerializerXmlAttributeOverride参数,例如

XmlAttributeOverrides overrides = new XmlAttributeOverrides();
XmlAttributes attributes = new XmlAttributes();
attributes.XmlIgnore = true;
overrides.Add(typeof(Example), "x_field", attributes);

XmlSerializer xs = new XmlSerializer(typeof(Example), overrides);
Run Code Online (Sandbox Code Playgroud)