C# 類型的預設值(C# 引用)Default values of C# types (C# reference)

下列表格顯示 C# 型別的預設值:The following table shows the default values of C# types:

類型Type 預設值Default value
任何參考類型Any reference type null
任何內建整數數值型別Any built-in integral numeric type 0 (零)0 (zero)
任何內建浮點數值型別Any built-in floating-point numeric type 0 (零)0 (zero)
Boolbool false
字元char '\0' (U+0000)'\0' (U+0000)
枚舉enum 這個值是由運算式 (E)0 所產生,其中 E 是列舉識別碼。The value produced by the expression (E)0, where E is the enum identifier.
structstruct 這個值是藉由將所有實值型別欄位設定為其預設值,並將所有參考型別欄位設定為 null 所產生。The value produced by setting all value-type fields to their default values and all reference-type fields to null.
任何可為 Null 的值型別Any nullable value type HasValue 屬性是 false 且未定義 Value 屬性的執行個體。An instance for which the HasValue property is false and the Value property is undefined. 該預設值也稱為空數值型別的值。That default value is also known as the null value of a nullable value type.

使用default運算子組建類型的預設值,如以下示例所示:Use the default operator to produce the default value of a type, as the following example shows:

int a = default(int);

從 C# 7.1 開始,可以使用default文本初始化具有其類型的預設值的變數:Beginning with C# 7.1, you can use the default literal to initialize a variable with the default value of its type:

int a = default;

針對值型別,隱含無參數建構函式也會產生型別的預設值,如下列範例所示:For a value type, the implicit parameterless constructor also produces the default value of the type, as the following example shows:

var n = new System.Numerics.Complex();
Console.WriteLine(n);  // output: (0, 0)

在運行時,如果System.Type實例表示數值型別,則可以使用Activator.CreateInstance(Type)方法調用無參數建構函式以獲取類型的預設值。At run time, if the System.Type instance represents a value type, you can use the Activator.CreateInstance(Type) method to invoke the parameterless constructor to obtain the default value of the type.

C# 語言規格C# language specification

如需詳細資訊,請參閱 C# 語言規格的下列幾節:For more information, see the following sections of the C# language specification:

另請參閱See also