我的类属性具有将被序列化的默认值。
public class DeclaredValue
{
[XmlElement(ElementName = "Amount", DataType = "double", IsNullable = false), DefaultValue(999)]
public double Amount { get; set; }
[XmlElement(ElementName = "Reference2", DataType = "string", IsNullable = false), DefaultValue("")]
public string Reference2 { get; set; }
}
因此我们创建 DeclaredValue 类的实例并为 Reference2 属性提供值,并且不为 Amount 分配任何内容。所以当我们序列化 DeclaredValue 类时,在我的 xml 中找不到数量的标签。我提到了金额“999”的默认值,以及为什么它在序列化中不起作用。我希望如果不为金额分配任何内容,那么 amoun 标签应该在我的 xml 中具有默认值。
要做到这一点,我需要用什么方式来装饰 amount 属性,如果用户没有为这个属性分配任何东西,它在序列化后总是带有 xml 中的默认值。
请指导我需要更改代码以获得所需的输出。
最佳答案
根据 note on MSDN :
A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.
有点意外的是DefaultValue只规定了对象的写入,等于DefaultValue的成员不会被写出。
您仍然必须在加载自己之前或之后初始化成员,例如在构造函数中。
关于c# - XML 序列化和 DefaultValue ("") c# 中的相关问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5882164/