c# - XML 序列化和 DefaultValue ("") c# 中的相关问题

标签 c# .net xml-serialization default-value

我的类属性具有将被序列化的默认值。

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/

相关文章:

.net - 无尽的动画?

c# - XmlSerializer 无法反序列化使用同一序列化程序序列化的 XML

c# - 无法使用命名空间反序列化 XmlArray

c# - 如何从列表中获取随机项目

c# - 确定是否通过window.open()命令打开了aspx页面

c# - 如何使用 JSON.NET 遍历嵌套字典?

c# - 如何输出exe使用的所有.NET框架DLL

.net - 基类中的 XmlText 属性破坏了序列化

c# - 在 .net 中获取 facebook 广告 api 错误

c# - 带有检查空元素的 XML 到 LINQ