为什么需要为 int 和 Data 而不是为 String 设置 Web Service DataMember 的指定属性 [英] Why does a Web Service DataMember's Specified Attribute need to be set for int and Data but not for String
问题描述
我通过 WCF 创建了一个 Web 服务.然后我将其作为 Web 服务公开,使其可用于 .NET 2.0 应用程序.我使用 DataMember 创建了一些 DataContract,可用于公开的 OperationContract.
I have created a web service via WCF. Then I exposed it as a web service to make it usable with a .NET 2.0 application. I created some DataContract with DataMember that could be used for by the exposed OperationContract.
我注意到,当我尝试创建要在 Web 服务中传递的 DataClass 时,每个 DataContract 属性现在对每个成员都有一个合作伙伴指定"属性.
I notice that when I try to create DataClass to be passed in the web service that each DataContract attribute now has a partner "Specified" attribute for each member.
例如:
[DataContract]
public class Sales
{
[DataMember]
public int InvoiceNo;
...
}
当我在 Web 服务客户端中创建 Sales 的实例时.我得到名为 InvoiceNo 和 InvoiceNoSpecified 的属性.
When I create an instance of Sales in the web service client. I get attribute named InvoiceNo and InvoiceNoSpecified.
现在我的问题是,当属性为字符串类型时,我不需要将相应的指定"属性设置为true,但是当属性类型为int或DateTime时,如果我不设置相应的指定"属性为true,该值在web 服务主机中变为null.有没有办法避免设置 Specified 属性?因为我需要在代码中的很多地方调用 Web 服务函数.跟踪它们真的很难.
Now here is my question, when the attribute is of type string, I do not need to set the corresponding "Specified" attribute to true, but when the attribute type is a int or DateTime, if I do not set the corresponding "Specified" attribute to true, the value becomes null in the web service host. Is there a way to avoid setting the Specified attribute? Cause I need to call the web service functions in a lot of places in my code. It would really be difficult to keep track of them all.
推荐答案
DataMember 属性的默认参数为:
The default parameters for the DataMember attribute are:
bool EmitDefaultValue (default true)
bool IsRequired (default false)
如果您公开的属性是不可为空的值类型,您应该使用:
If the property you are exposing is a non-nullable value type you should use:
[DataMember(IsRequired = true)]
public int InvoiceNo;
这篇关于为什么需要为 int 和 Data 而不是为 String 设置 Web Service DataMember 的指定属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!