預設值表達式會產生類型的 預設值 。 默認值表達式有兩種: 預設運算符 呼叫和 預設常值。
您也可以使用 default 關鍵詞作為 語句內switch的預設案例標籤。
default 運算符
default 運算子的引數必須是型別名稱或型別參數,如下列範例所示:
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 值表達式會產生與表達式相同的值, default(T) 其中 T 是推斷的類型。 您可以在下列任何情況下使用 default 常值:
- 在變數的指派或初始化中。
- 在 選擇性方法參數的預設值宣告中。
- 在方法呼叫中,提供自變數值。
-
return在語句中,或做為表達式主體成員中的表達式。
下列範例顯示常值的用法 default :
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) ]
小提示
使用 .NET 樣式規則 IDE0034 指定程式代碼基底中常值用法的 default 喜好設定。
C# 語言規格
另請參閱
- C# 運算子與運算式
- C# 類型的預設值
- .NET 中的 泛型