DataMemberAttribute.EmitDefaultValue 属性
定义
获取或设置一个值,该值指定是否序列化正在序列化的字段或属性的默认值。Gets or sets a value that specifies whether to serialize the default value for a field or property being serialized.
public:
property bool EmitDefaultValue { bool get(); void set(bool value); };
public bool EmitDefaultValue { get; set; }
member this.EmitDefaultValue : bool with get, set
Public Property EmitDefaultValue As Boolean
属性值
如果应该在序列化流中生成成员的默认值,则为 true;否则为 false。true if the default value for a member should be generated in the serialization stream; otherwise, false. 默认值为 true。The default is true.
示例
下面的示例演示了在各种字段中将 EmitDefaultValue 属性设置为 false。The following example shows the EmitDefaultValue property set to false on various fields.
[DataContract]
public class Employee
{
// The CLR default for as string is a null value.
// This will be written as <employeeName xsi:nill="true" />
[DataMember]
public string EmployeeName = null;
// This will be written as <employeeID>0</employeeID>
[DataMember]
public int employeeID = 0;
// The next three will not be written because the EmitDefaultValue = false.
[DataMember(EmitDefaultValue = false)]
public string position = null;
[DataMember(EmitDefaultValue = false)]
public int salary = 0;
[DataMember(EmitDefaultValue = false)]
public int? bonus = null;
// This will be written as <targetSalary>57800</targetSalary>
[DataMember(EmitDefaultValue = false)]
public int targetSalary = 57800;
}
<DataContract()> _
Public Class Employee
' The CLR default for as string is a null value.
' This will be written as <employeeName xsi:nil="true" />
<DataMember()> _
Public employeeName As String = Nothing
' This will be written as <employeeID>0</employeeID>
<DataMember()> _
Public employeeID As Integer = 0
' The next two will not be written because the EmitDefaultValue = false.
<DataMember(EmitDefaultValue := False)> Public position As String = Nothing
<DataMember(EmitDefaultValue := False)> Public salary As Integer = 0
' This will be written as <targetSalary>555</targetSalary> because
' the 555 does not match the .NET default of 0.
<DataMember(EmitDefaultValue := False)> Public targetSalary As Integer = 555
End Class
注解
在 .NET Framework 中,类型具有默认值的概念。In the .NET Framework, types have a concept of default values. 例如,对于任何引用类型,默认值为 null ,而对于整数类型,则为0。For example, for any reference type the default value is null, and for an integer type it is 0. 如果某个数据成员设置为其默认值,有时会希望序列化数据中不包含该数据成员。It is occasionally desirable to omit a data member from the serialized data when it is set to its default value. 为此,请将 EmitDefaultValue 属性设置为 false(其默认值为 true)。To do this, set the EmitDefaultValue property to false (it is true by default).
备注
建议不要将 EmitDefaultValue 属性设置为 false。Setting the EmitDefaultValue property to false is not a recommended practice. 仅在有执行此操作的特定需要(例如实现互操作性或减少数据大小)时,才应该进行这样的设置。It should only be done if there is a specific need to do so (such as for interoperability or to reduce data size).