DataMemberAttribute.EmitDefaultValue 属性

定义

获取或设置一个值,该值指定是否序列化正在序列化的字段或属性的默认值。

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

示例

下面的示例演示了在各种字段中将 EmitDefaultValue 属性设置为 false

[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 中,类型具有默认值的概念。 例如,对于任何引用类型,默认值为 null,对于整数类型,默认值为 0。 如果某个数据成员设置为其默认值,有时会希望序列化数据中不包含该数据成员。 为此,请将 EmitDefaultValue 属性设置为 false(其默认值为 true)。

注意

建议不要将 EmitDefaultValue 属性设置为 false。 仅在有执行此操作的特定需要(例如实现互操作性或减少数据大小)时,才应该进行这样的设置。

适用于