![](/img/trans.png)
[英]XmlSerializer with parameterless constructor with no public properties or fields… Is it possible?
[英]XmlSerializer ignore public fields?
我正在使用一些現有的代碼,定義如下。
class Example
{
public float x_field;
public float x_property
{
get { return x_field; }
set { x_field = value; }
}
}
為什么它這樣定義我不知道,但我無法改變它的實現。 問題是,當我序列化它時,我顯然在xml輸出中得到了兩個值。 如果我無法修改'Example'類,怎么能阻止這種情況發生?
我希望Serializer只輸出公共屬性而不是公共字段。
您可以使用XmlSerializer的XmlAttributeOverride參數,例如
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);
我會使用一個中間對象。 您可以控制以創建要序列化的確切模型。
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.