[英]XML Serialization of public property backing private field in C#
I'm hoping someone can help answer this for me, as I've been pulling my hair out all morning trying to track down a solution to this issue. 我希望有人可以帮我解决这个问题,因为整个上午我一直在努力寻找解决方案。
I have a class that needs to be serialized to XML. 我有一个需要序列化为XML的类。 The XML Serialization works as long as I'm serializing a simple public property.
只要我要序列化一个简单的公共属性,XML序列化就可以工作。 However, if I have a public property that acts as a getter for a private field that backs it, the public property isn't serialized (despite being decorated with
[XmlAttribute()]
). 但是,如果我有一个公共属性充当支持它的私有字段的获取器 ,则该公共属性不会被序列化(尽管使用
[XmlAttribute()]
装饰)。 I've combed through MSDN and StackOverflow looking for answers, but to no avail. 我已经通过MSDN和StackOverflow进行了梳理,以寻找答案,但无济于事。 I've mocked up an example below.
我在下面模拟了一个例子。
[Serializable()]
[XmlRoot("foobar")]
public class FooBar
{
[XmlAttribute("foo")]
public string Foo { get; set; }
private bool bar;
[XmlAttribute("bar")]
public string Bar
{
get { return ConvertBoolToYesNo(bar); }
}
public FooBar()
{
Foo = "foo";
bar = true;
}
public string ConvertBoolToYesNo(bool boolToConvert)
{
if(boolToConvert == true)
return "yes";
else
return "no";
}
} }
This returns <?xml version="1.0" encoding="us-ascii"?><foobar foo="foo" />
when I would expect it to return <?xml version="1.0" encoding="us-ascii"?><foobar foo="foo" bar="yes" />
. 当我希望它返回
<?xml version="1.0" encoding="us-ascii"?><foobar foo="foo" bar="yes" />
时,它将返回<?xml version="1.0" encoding="us-ascii"?><foobar foo="foo" />
<?xml version="1.0" encoding="us-ascii"?><foobar foo="foo" bar="yes" />
。 Any suggestions would be appreciated. 任何建议,将不胜感激。
Thanks in advance! 提前致谢!
Check this answer right here: 在此处检查此答案:
Why are properties without a setter not serialized 为什么没有setter的属性未序列化
Seems like it is a serializer limitation (by design) when you have "readonly" properties, try adding a "setter" and it might work. 当您具有“只读”属性时,似乎是序列化程序的限制(根据设计),请尝试添加“设置器”,它可能会起作用。
我相信XMLSerializer不能序列化只读属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.