0Pricing
C# Academy · 课时

注解:?、!、MaybeNull 与 NotNull

使用 ? 表示可空类型,使用 ! 抑制空值警告,并使用 MaybeNull 和 NotNullWhen 等属性进行精确的流分析。

注解:?、!、MaybeNull 与 NotNull 是 CoddyKit 上的免费 C# Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 C# Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 C# Academy 课程共包含 4 节课。

超越 ? 和 !:可空性特性

基本的 ? 注释和空值检查可以处理大多数情况,但某些模式需要表达能力更强的注释。System.Diagnostics.CodeAnalysis 命名空间提供了一些特性,让编译器能够更深入地了解空值流。

MaybeNull 与 NotNull

[MaybeNull] 告诉编译器,不可空返回类型在实际运行中可能为空(例如泛型方法)。[NotNull] 保证可空参数在调用完成后不会为空。

using System.Diagnostics.CodeAnalysis;

// [MaybeNull]: return might be null even though T is non-nullable
[return: MaybeNull]
public T Find<T>(int id)
{
    // Returns default(T) which is null for reference types
    return _cache.TryGetValue(id, out var val) ? val : default!;
}

// [NotNull]: after this call, output is guaranteed non-null
public static void EnsureNotNull<T>(
    [NotNull] ref T? value,
    T defaultValue) where T : class
{
    value ??= defaultValue;
}

NotNullWhen:条件性不可空

[NotNullWhen(true)] 告诉编译器,当方法返回 true 时,输出参数不为空。标准的 TryParse 模式就是这样进行注释的。

using System.Diagnostics.CodeAnalysis;

public static bool TryParseEmail(
    string? input,
    [NotNullWhen(true)] out string? email)
{
    if (input?.Contains('@') == true)
    {
        email = input.Trim().ToLower();
        return true;
    }
    email = null;
    return false;
}

// Usage — no warning after true check:
if (TryParseEmail(raw, out var email))
    Console.WriteLine(email.Length); // safe — email is non-null here

MaybeNullWhen:条件性可空

[MaybeNullWhen(false)] 与之相反:当方法返回 false 时,输出值可能为空。它用于字典的 TryGetValue 模式。

// This is how Dictionary<K,V>.TryGetValue is annotated:
public bool TryGetValue(
    TKey key,
    [MaybeNullWhen(false)] out TValue value)
{ ... }

// Usage:
if (!dict.TryGetValue("key", out var value))
    return; // early return — value is null in this branch

Console.WriteLine(value.Length); // safe after the guard

AllowNull 与 DisallowNull

在不可空属性上使用 [AllowNull],允许调用方向其传入空值(例如将空值转换为空字符串的 setter)。[DisallowNull] 则禁止在可空类型上使用空值。

public class Config
{
    private string _name = "";

    // Allow setting null (setter converts null -> empty)
    [AllowNull]
    public string Name
    {
        get => _name;
        set => _name = value ?? "";
    }

    // Getter always returns non-null: fine
    // Setter accepts null: [AllowNull] tells compiler that's OK
}

NotNullIfNotNull:传递可空性

[NotNullIfNotNull(paramName)] 表示:如果参数 X 不为空,则返回值也不为空。它适用于转换函数。

[return: NotNullIfNotNull(nameof(value))]
public static string? Normalize(string? value)
{
    return value?.Trim().ToLower();
}

// Usage:
string  name = "  Alice  ";
string  norm1 = Normalize(name)!; // guaranteed non-null
string? raw   = GetRaw();
string? norm2 = Normalize(raw);   // still nullable (raw might be null)

DoesNotReturn

[DoesNotReturn] 标记一个始终抛出异常的方法。编译器知道调用后的代码不可达,因此会抑制多余的空值警告。

using System.Diagnostics.CodeAnalysis;

[DoesNotReturn]
public static void ThrowNotFound(int id)
    => throw new KeyNotFoundException($"Entity {id} not found");

// Usage — no null warning after the call:
var order = _db.Orders.Find(id);
if (order is null) ThrowNotFound(id);

Console.WriteLine(order.Id); // no CS8602 — compiler knows ThrowNotFound threw

MemberNotNull:字段的后置条件

[MemberNotNull] 告诉编译器,某个方法返回后,可以保证指定字段不为空。它适用于延迟初始化辅助方法。

public class DataLoader
{
    private string? _data;

    [MemberNotNull(nameof(_data))]
    private void EnsureLoaded()
    {
        if (_data is null)
            _data = LoadFromFile();
    }

    public string GetData()
    {
        EnsureLoaded();
        return _data; // no CS8603 — compiler knows _data is set
    }
}

组合注释

可以组合多个特性,以构建精确的 API 契约。下面是一个组合多个特性的流式防护辅助方法。

public static class Guard
{
    [return: NotNull]
    public static T NotNull<T>(
        [NotNull][AllowNull] T? value,
        [CallerArgumentExpression(nameof(value))] string? name = null)
        where T : class
    {
        ArgumentNullException.ThrowIfNull(value, name);
        return value;
    }
}

// Usage:
var product = Guard.NotNull(await _repo.FindAsync(id));
Console.WriteLine(product.Name); // no warning

空值运算符:?. ?? ??=

空值条件运算符(?.)、空值合并运算符(??)和空值合并赋值运算符(??=)可以编写简洁且空值安全的代码,无需冗长的 if 检查。

string? name = GetName();

// ?. safe navigation
int? len = name?.Length;
string? upper = name?.ToUpper().Trim();

// ?? default value
string display = name ?? "Anonymous";

// ??= lazy init
name ??= "Default";

// Chaining
string result = user?.Profile?.DisplayName ?? user?.Name ?? "Guest";

快速检查

在输出参数上使用 [NotNullWhen(true)] 会告诉编译器什么信息?

回顾:可空性注释

要点:

  • [NotNullWhen(true)]:TryParse 模式——返回 true 时值不为空
  • [MaybeNull]:不可空类型仍可能返回空值(泛型默认值)
  • [DoesNotReturn]:方法始终抛出异常——后续代码不可达
  • [MemberNotNull]:方法返回后保证字段已设置
  • ?.、??、??=:简洁地进行空值安全导航和提供默认值

常见问题解答

「注解:?、!、MaybeNull 与 NotNull」课时是免费的吗?

是的 — 「注解:?、!、MaybeNull 与 NotNull」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 C# Academy 课程的其余内容,请升级到 CoddyKit PRO。 C# Academy 课程共包含 4 节课。

「注解:?、!、MaybeNull 与 NotNull」这节课中我会学到什么?

使用 ? 表示可空类型,使用 ! 抑制空值警告,并使用 MaybeNull 和 NotNullWhen 等属性进行精确的流分析。 你通过在浏览器中直接运行的动手代码来练习 C# Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 C# Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 C# Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「注解:?、!、MaybeNull 与 NotNull」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 C# Academy 课中编写并运行代码吗?

能。每节 C# Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 启用并理解 NRT
  2. 注解:?、!、MaybeNull 与 NotNull
  3. 空值条件与空值合并运算符
  4. 将代码库迁移到 NRT
← 返回 C# Academy