简体   繁体   English

XmlSerializer忽略公共字段?

[英]XmlSerializer ignore public fields?

I am using some existing code that is defined as follows. 我正在使用一些现有的代码,定义如下。

class Example
{
    public float x_field;
    public float x_property
    {
        get { return x_field; }
        set { x_field = value; }
    }
}

Why its defined like this I don't know, but I'm unable to change its implementation. 为什么它这样定义我不知道,但我无法改变它的实现。 The problem, is that when I serialize it, I obviously get both values in the xml output. 问题是,当我序列化它时,我显然在xml输出中得到了两个值。 How can I stop this from occurring if I can't modify the 'Example' class? 如果我无法修改'Example'类,怎么能阻止这种情况发生?

I want the Serializer to only output public properties and not public fields. 我希望Serializer只输出公共属性而不是公共字段。

You could use the XmlAttributeOverride parameter of XmlSerializer eg 您可以使用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);

I would use an intermediate object. 我会使用一个中间对象。 One that you can control to create the exact model you want to serialize. 您可以控制以创建要序列化的确切模型。

class IntermdeiateModel
{
     public float x+property {get;set;}
}
....

return Serializer.Serialze(GetAllEamples().Select(e => new IntermdeiateModel { x_property = e.x_property));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM