XML序列化和默认值("")在C#中的相关问题 [英] XML serialization and DefaultValue("") related problem in c#

查看:436
本文介绍了XML序列化和默认值("")在C#中的相关问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的类属性有默认值,这将是序列化。

my class property has default value which will be serialize.

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类的实例,并提供价值给定2财产,不指定任何的金额。所以当我们序列化类DeclaredValue那么没有标记发现金额在我的XML。我提到的量999的默认值,那么为什么它不序列化工作。我想,如果没有指定任何东西量的Amoun然后标记应该出现在我的XML使用默认值。

so we create instance of DeclaredValue class and provide value for Reference2 property and do not assign anything for Amount. so when we serialize the class DeclaredValue then no tag found for amount in my xml. i mention default value for amount "999" then why it does not work in serialization. i want that if do not assign anything for amount then amoun tag should be there in my xml with default value.

要做到这一点有什么办法,我需要来装饰它总是序列化后带有默认值的xml量属性,如果用户没有指定任何此属性。

to do this what way i need to decorate the amount property that it always comes with default value in xml after serialization if user do not assign anything to this property.

请指导我什么,我需要在code改变让我所需的输出。

please guide me what i need to change in the code to get my desired output.

推荐答案

按照笔记MSDN上

一个DefaultValueAttribute会的不可以的原因   会员自动   同属性的初始化   值。您必须设置初始值   在code。

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.

这篇关于XML序列化和默认值("")在C#中的相关问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆