在 C# 中,null字面量用于表示值的缺失。_可空_类型是一种允许取值为null的类型。
在 C# 8.0 之前,引用类型始终可以为空,而值类型则不行。只要在值类型后面加上一个问号(?),就能把它变成可空类型。
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
访问空变量的成员不会导致编译错误,但会在运行时抛出NullReferenceException。
string sentence = null;
// Throws NullReferenceException at runtime
sentence.Length;
为了解决这类常见的错误,C# 8 允许你启用一项功能,让引用类型默认不可为空:
string nonNullableReferenceType = "book";
nonNullableReferenceType = null; // Compile warning (no error!)
string? nullableReferenceType = "movie";
nullableReferenceType = null; // Valid as type is nullable
要想安全地处理可空值,在使用它们之前先检查它们是否为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"