C#笔记(十)---可为空引用类型(未完待续)

C#8.0 引入了“nullable reference types”和“non-nullable reference types”

引用不应为 null。

当变量不应为 null 时,编译器会强制执行规则,以确保在不首先检查它们是否为 null 的情况下,取消引用(dereference)这些变量是安全的:

  • 必须将变量初始化为非 null 值。
  • 变量永远不能赋值为 null。

引用可为 null。

当变量可以为 null 时,编译器会强制执行不同的规则以确保你已正确检查null reference:

  • 只有当编译器可以保证该值不为 null 时,才可以取消引用该变量。
  • 这些变量可以使用默认的 null 值进行初始化,也可以在其他代码中赋值为 null。

A reference can be null.
The compiler doesn't issue warnings when a reference-type variable is initialized to null, or later assigned null.
The compiler issues warnings when these variables are dereferenced without null checks.
A reference is assumed to be not null.
The compiler doesn't issue any warnings when reference types are dereferenced.
The compiler issues warnings if a variable is set to an expression that may be null.
警告将在编译时发出.
编译器不会在可为 null 的上下文中添加任何 null 检查或其他运行时构造。 在运行时,可为 null 的引用和不可为 null 的引用是等效的。

// A nullable reference type:
string? name;
// 若知道 name 变量不为 null 但编译器仍发出警告,则可以编写以下代码来覆盖编译器的分析:
name!.Length; 

Nullability of types

  • Nonnullable:无法将 null 分配给此类型的变量。 在取消引用之前,无需对此类型的变量进行 null 检查。
  • Nullable:可将 null 分配给此类型的变量。 在不首先检查 null 的情况下取消引用此类型的变量时发出警告。
  • Oblivious:“无视”是 C# 8.0 之前版本的状态。 可以取消引用或分配此类型的变量而不发出警告。
  • Unknown:“未知”通常针对类型参数,其中约束不告知编译器类型是否必须是“可为 null”或“不可为 null” 。
    变量声明中类型的为 Null 性由声明变量的“nullable context”控制。

Nullable contexts