为什么不建议使用[DataMember(EmitDefaultValue = false)]? [英] Why is using [DataMember(EmitDefaultValue = false)] not recommended?

查看:505
本文介绍了为什么不建议使用[DataMember(EmitDefaultValue = false)]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WCF中,您可以使用[DataContract][DataMember]属性定义合同,如下所示:

In WCF you can define a contract using the [DataContract] and [DataMember] attributes, like this:

[DataContract]
public class Sample 
{
    [DataMember(EmitDefaultValue = false, IsRequired = false)]
    public string Test { get; set; }
}

MSDN上的这篇文章指出:不建议使用EmitDefaultValue = false:

但是,我喜欢使用它,因为使用此构造生成的XML更干净.不指定此设置将导致:

However, i like to use this, because the XML that is generated using this construction is cleaner. Not specifying this setting results in:

<Sample>
    <Test xsi:nil="true"/>
</Sample>

在使用设置时,如果没有值,则忽略该元素:

while using the setting the element is ommited when there is no value:

<Sample>
</Sample>

我对该声明背后的原因感到好奇.特别是因为这两个XML代码片段看起来都和我一样(并且对于该合同,最后两个部分都可以正确地反序列化).

I'm curious to what the reasoning behind that statement is. Specifically since both snipptes of XML look equivalent to me (and both last part can be deserialized correctly for this contract).

此声明背后的原因是什么?

推荐答案

原因在您链接到文章的底部.简短的版本是:

The reason is at the bottom of the article that you link to. The short version is:

  • EmitDefaultValue设置为false时,它在架构中表示为Windows Communication Foundation(WCF)特有的注释.没有可互操作的方式来表示此信息.特别是,架构中的默认"属性不用于此目的,minOccurs属性仅受IsRequired设置影响,而nillable属性仅受数据成员的类型影响.

  • When the EmitDefaultValue is set to false, it is represented in the schema as an annotation specific to Windows Communication Foundation (WCF). There is no interoperable way to represent this information. In particular, the "default" attribute in the schema is not used for this purpose, the minOccurs attribute is affected only by the IsRequired setting, and the nillable attribute is affected only by the type of the data member.

架构中不存在要使用的实际默认值.由接收端点适当地解释缺少的元素.

The actual default value to use is not present in the schema. It is up to the receiving endpoint to appropriately interpret a missing element.

这篇关于为什么不建议使用[DataMember(EmitDefaultValue = false)]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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