C# 区分可以为 null 的类型和不可以为 null 的类型。可空值类型(int?)让值类型可以保存 null,(编译器功能)帮助捕获 null 缺陷,(、、)让处理可能为 null 的值变得清晰且安全 — 解决了普遍存在的 null 引用问题。
?.??!int x = 5; // a value type — CANNOT be null
int? y = null; // int? = Nullable<int> — CAN be null
if (y.HasValue) { int val = y.Value; } // check + access
int z = y ?? 0; // default if null
值类型通常不能为 null,但 int?(Nullable<int>)允许这样 — 常用于表示可选/缺失数据(例如可空数据库列)。
#nullable enable // (on by default in modern projects)
string name = null; // ⚠️ warning — string is non-nullable by default now
string? maybe = null; // ✅ string? explicitly allows null
void Use(string? s) {
Console.WriteLine(s.Length); // ⚠️ warning — s might be null (must check first)
}
启用可空引用类型后,编译器会跟踪哪些引用可以为 null(string?)以及哪些不能(string),并在你可能解引用 null 时发出警告 — 在编译时捕获 NullReferenceException 缺陷。这是现代 C# 的一个重要安全特性。
// ?. null-conditional — short-circuits to null instead of throwing
int? len = user?.Name?.Length; // null if user or Name is null (no exception)
user?.DoSomething(); // only calls if user isn't null
// ?? null-coalescing — provide a default
string name = input ?? "Anonymous";
name ??= "fallback"; // assign if currently null
// ! null-forgiving — assert non-null (suppress the warning; use carefully)
string definitelyNotNull = maybe!; // "I know it's not null" — no runtime check
null 条件操作符(?.)安全地访问可能为 null 的值的成员(返回 null 而不是抛异常),?? 提供默认值 — 一起使 null 处理变得清晰且安全。
空引用处理是编写健壮 C# 最重要的方面之一,因为 NullReferenceException(