在 C# 中,null常值用來表示值不存在。_可為 null 的_型別就是允許null值的型別。
在 C# 8.0 之前,參考型別一律可為 null,而值型別則不行。只要在值型別後面加上問號(?),就能讓它變成可為 null 的型別。
string nullableReferenceType = "hello";
nullableReferenceType = null; // Valid as type is nullable
int nonNullableValueType = 5;
nonNullableValueType = null; // Compile error as type is not nullable
int? nullableValueType = 5; // Define nullable value type
nullableValueType = null; // Valid as type is nullable
存取 null 變數的成員並不會造成編譯錯誤,但會在執行階段擲回NullReferenceException:
string sentence = null;
// Throws NullReferenceException at runtime
sentence.Length;
為了避免這類常見的錯誤,C# 8 允許你選擇啟用一項功能,讓參考型別預設為不可為 null:
string nonNullableReferenceType = "book";
nonNullableReferenceType = null; // Compile warning (no error!)
string? nullableReferenceType = "movie";
nullableReferenceType = null; // Valid as type is nullable
若要安全地處理可為 null 的值,請在使用前先檢查它們是否為null:
string NormalizedName(string? name)
{
if (name == null)
{
return "UNKNOWN";
}
// Value is not null at this point, so no compile warning
// and no runtime NullReferenceException being thrown
return name.ToUpper();
}
NormalizedName(null); // => "UNKNOWN"
NormalizedName("Elisabeth"); // => "ELISABETH"
??運算子讓你能在值為null時回傳預設值:
string? name1 = "John";
name1 ?? "Paul"; // => "John"
string? name2 = null;
name2 ?? "George"; // => "George"
?.運算子讓你可以安全地在可能為null的值上呼叫成員:
string? fruit = "apple";
fruit?.Length; // => 5
string? vegetable = null;
vegetable?.Length; // => null
在這個練習中,你將撰寫程式碼,為工廠員工列印名牌。
員工有 ID、姓名和部門名稱。員工名牌標籤的格式如下:"[id] - name - DEPARTMENT"。請實作(static)Badge.Print() 方法,回傳員工的名牌標籤:
Badge.Print(734, "Ernest Johnny Payne", "Strategic Communication");
// => "[734] - Ernest Johnny Payne - STRATEGIC COMMUNICATION"
請注意,部門名稱在標籤上要轉為大寫。
由於電腦系統的小毛病,新員工開始在工廠工作時,偶爾還沒有 ID。因為名牌是必需的,他們會拿到一張沒有 ID 前綴的臨時名牌。請修改(static)Badge.Print() 方法,讓它支援還沒有 ID 的新員工:
Badge.Print(id: null, "Jane Johnson", "Procurement");
// => "Jane Johnson - PROCUREMENT"
即使是工廠老闆,也必須隨時佩戴名牌。不過,老闆沒有部門。在這種情況下,標籤應該列印 "OWNER",而不是部門名稱。請修改(static)Badge.Print() 方法,為老闆列印標籤:
Badge.Print(254, "Charlotte Hale", department: null);
// => "[254] - Charlotte Hale - OWNER"
請注意,老闆也可能同時是新員工:
Badge.Print(id: null, "Charlotte Hale", department: null);
// => "Charlotte Hale - OWNER"