WCF DataContract - marking member IsRequired=false

青春壹個敷衍的年華 提交于 2020-01-02 05:22:07

问题


I have a contract as follows:

[DataContract]
public class MyObj
{
    [DataMember(IsRequired=true)]
    public string StrA {get; private set;}

    [DataMember(IsRequired=false)]
    public string StrB {get; private set;}
}

What exactly does IsRequired mean? Does IsRequired=false mean that I can pass an instance of MyObj across the wire with StrB unitialized or does it mean that I can pass an instance of MyObj across the wire with StrB absent?

If the latter, how do I actually instantiate + send across an instance of MyObj without StrB?


回答1:


DataMember's IsRequired tells the serialization engine whether the value of StrB must be presented in the underlying XML.

So over the wire you can get <MyObj></MyObj> and it will deserialize into an MyObj instance just fine.

Edit: You can't actually initialize a instance of MyObj without StrB being present. The use for this is compatibility and extensibility. For example, maybe the client doesn't have the updated MyObj version and it doesn't have StrB present. In this case, the server code can mark StrB as not requried and there will not be a serialization exception when a message is received on the server side.




回答2:


how do I actually instantiate + send across an instance of MyObj without StrB?

As I just mentioned in WCF and Anonymous Types , you can use [DataMember(EmitDefaultValue=false)]. This will make sure that when the data member is at its default value (e.g. null for strings), it won't be emitted.



来源:https://stackoverflow.com/questions/1566803/wcf-datacontract-marking-member-isrequired-false

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!