C# Nullable 注解,如果参数不为空,则方法返回不为空

Mic*_*han 19 .net c# nullable nullable-reference-types

如果输入不为空,如何告诉编译器以下扩展方法返回不为空?

public static string? SomeMethod(this string? input)
{
    if (string.IsNullOrEmpty(input))
        return input;

    // Do some work on non-empty input
    return input.Replace(" ", "");
}
Run Code Online (Sandbox Code Playgroud)

Svy*_*liv 35

使用以下属性:

[return: NotNullIfNotNull(nameof(input))]
public static string? SomeMethod(this string? input)
{
   ...
}
Run Code Online (Sandbox Code Playgroud)

进一步阅读:C# 编译器解释的空状态静态分析的属性

  • 从 C# 11 开始,您可以在属性中使用“nameof”,如下所示“[return: NotNullIfNotNull(nameof(input))]” (4认同)