强制XML序列化序列化只读属性 [英] Force XML serialization to serialize readonly property
本文介绍了强制XML序列化序列化只读属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C#中,我有一个具有衍生性质应该通过XML序列化类。然而,XML序列化(默认)不序列读取=仅属性。我可以解决这个定义,像这样一个空的setter:
In C#, I have a class which has a derived property that should be serialized via XML. However, XML serialization (by default) doesn't serialize read=only properties. I can work around this by defining an empty setter like so:
public virtual string IdString
{
get { return Id.ToString("000000"); }
set { /* required for xml serialization */ }
}
但有一个更清洁更语义正确的方式,总之我自己写了ISerializable实现?
But is there a cleaner more semantically correct way, short of writing my own ISerializable implementation?
推荐答案
老实说这似乎并不算太坏对我来说,只要它是记录
Honestly this doesn't seem too bad to me as long as it is documented
您或许应该抛出一个异常,如果setter方法实际上是所谓的:
You should probably throw an exception if the setter is actually called:
/// <summary>
/// Blah blah blah.
/// </summary>
/// <exception cref="NotSupportedException">Any use of the setter for this property.</exception>
/// <remarks>
/// This property is read only and should not be set.
/// The setter is provided for XML serialisation.
/// </remarks>
public virtual string IdString
{
get
{
return Id.ToString("000000");
}
set
{
throw new NotSupportedException("Setting the IdString property is not supported");
}
}
这篇关于强制XML序列化序列化只读属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文