default value 表达式(C# 参考)default value expressions (C# reference)

default value 表达式生成类型的默认值A default value expression produces the default value of a type. 有两种类型的 default value 表达式:default 运算符调用和 default 文本There are two kinds of default value expressions: the default operator call and a default literal.

你还可以将 default 关键字用作 switch 语句中的默认用例标签。You also use the default keyword as the default case label within a switch statement.

default 运算符default operator

default 运算符的实参必须是类型或类型形参的名称,如以下示例所示:The argument to the default operator must be the name of a type or a type parameter, as the following example shows:

Console.WriteLine(default(int));  // output: 0
Console.WriteLine(default(object) is null);  // output: True

void DisplayDefaultOf<T>()
{
    var val = default(T);
    Console.WriteLine($"Default value of {typeof(T)} is {(val == null ? "null" : val.ToString())}.");
}

DisplayDefaultOf<int?>();
DisplayDefaultOf<System.Numerics.Complex>();
DisplayDefaultOf<System.Collections.Generic.List<int>>();
// Output:
// Default value of System.Nullable`1[System.Int32] is null.
// Default value of System.Numerics.Complex is (0, 0).
// Default value of System.Collections.Generic.List`1[System.Int32] is null.

default 文本default literal

从 C# 7.1 开始,当编译器可以推断表达式类型时,可以使用 default 文本生成类型的默认值。Beginning with C# 7.1, you can use the default literal to produce the default value of a type when the compiler can infer the expression type. default 文本表达式生成与 default(T) 表达式(其中,T 是推断的类型)相同的值。The default literal expression produces the same value as the default(T) expression where T is the inferred type. 可以在以下任一情况下使用 default 文本:You can use the default literal in any of the following cases:

下面的示例演示 default 文本的用法:The following example shows the usage of the default literal:

T[] InitializeArray<T>(int length, T initialValue = default)
{
    if (length < 0)
    {
        throw new ArgumentOutOfRangeException(nameof(length), "Array length must be nonnegative.");
    }

    var array = new T[length];
    for (var i = 0; i < length; i++)
    {
        array[i] = initialValue;
    }
    return array;
}

void Display<T>(T[] values) => Console.WriteLine($"[ {string.Join(", ", values)} ]");

Display(InitializeArray<int>(3));  // output: [ 0, 0, 0 ]
Display(InitializeArray<bool>(4, default));  // output: [ False, False, False, False ]

System.Numerics.Complex fillValue = default;
Display(InitializeArray(3, fillValue));  // output: [ (0, 0), (0, 0), (0, 0) ]

C# 语言规范C# language specification

有关详细信息,请参阅 C# 语言规范中的 默认值表达式部分。For more information, see the Default value expressions section of the C# language specification.

有关 default 文本的详细信息,请参阅功能建议说明For more information about the default literal, see the feature proposal note.

请参阅See also