C# 将EmitDefaultValue应用于属性。如何指定默认值?
可能重复:C# 将EmitDefaultValue应用于属性。如何指定默认值?,c#,.net,wcf,web-services,attributes,C#,.net,Wcf,Web Services,Attributes,可能重复: 考虑以下几点: [DataContract] public class MyType { [DataMember(EmitDefaultValue = true)] public string MyStr = "DefVal"; } [DataContract] public class MyType { [DataMember(EmitDefaultValue = true)] public string MyStr { get { ...
考虑以下几点:
[DataContract]
public class MyType {
[DataMember(EmitDefaultValue = true)]
public string MyStr = "DefVal";
}
[DataContract]
public class MyType {
[DataMember(EmitDefaultValue = true)]
public string MyStr {
get { ... }
set { ... }
}
}
在上面的代码中,我可以指定赋值后使用的默认值
现在考虑以下内容:
[DataContract]
public class MyType {
[DataMember(EmitDefaultValue = true)]
public string MyStr = "DefVal";
}
[DataContract]
public class MyType {
[DataMember(EmitDefaultValue = true)]
public string MyStr {
get { ... }
set { ... }
}
}
如何在此处指定默认值
谢谢
EmitDefaultValue
说,如果您不指定该值,它仍然应该为.NET类型添加具有默认值的元素。如果是字符串
,它将类似于:
<MyStr xsi:nil="true" />
您的第一个示例没有设置默认值。它设置公共值,因为它与任何其他赋值相同,如果传入消息包含null
,它将覆盖该初始值
如果需要使用任何特殊值而不是null(序列化之前或反序列化之后),请使用链接副本中所述的用[onserialization]
和[onserialized]
属性修饰的方法