代码检查:根据可空引用类型的注解,条件访问限定符表达式不为 null
如果启用了 可空引用类型 (NRT) ,此检查会报告对于由于可空上下文和注解保证不会为 null 的表达式中冗余的条件访问运算符(?.)。
在下面的示例中, GetRnd() 被声明为返回类型为 Rnd (没有 ? 注解),这意味着在可空感知上下文中,返回值永远不会为 null。 由于 rnd 获取了此返回值,它也将被视为非可空,从而使 rnd?.TrueOrFalse 中的条件访问运算符 ?. 变得不必要。 因此,JetBrains Rider 建议将 rnd?.TrueOrFalse 替换为 rnd.TrueOrFalse。
#nullable enable
class Test {
Test()
{
var rnd = GetRnd();
if(rnd?.TrueOrFalse is true)
Console.WriteLine("True");
}
Rnd GetRnd() => new Rnd();
}
public class Rnd
{
public bool TrueOrFalse =>
new Random().Next(2) == 0;
}
#nullable enable
class Test {
Test()
{
var rnd = GetRnd();
if(rnd.TrueOrFalse is true)
Console.WriteLine("True");
}
Rnd GetRnd() => new Rnd();
}
public class Rnd
{
public bool TrueOrFalse =>
new Random().Next(2) == 0;
}
NRT 提高了可空性分析的整体精度,但在某些情况下,NRT 合约可能会被违反,例如,当值来自没有 #可为 null 上下文的代码时。 在这种情况下,您可能会收到可空性检查的误报警告。 您可以选择忽略可空 API 合约,仅在代码中对值的先前操作保证其可以或不可以为 null 时报告问题。
您可以直接从 Alt+Enter 菜单更改此行为:

…或者在 JetBrains Rider 设置 的 页面上使用 可空引用类型的警告模式 选项。
当 JetBrains Rider 忽略可空 API 合约时,可空性分析依赖程序控制流来报告冗余的空检查。 它将使用另一个检查来完成此任务。 例如:
var myString = ApiMethod();
if (myString is null)
throw new ApplicationException("the string is null");
// warning 'Expression is always true'
// 'myString' cannot be null because it's already checked for null in our code
if (myString != null)
Console.WriteLine(myString);
有关 NRT 及其在 JetBrains Rider 中的支持的更多信息,请观看此网络研讨会录制:
最后修改日期: 2025年 9月 26日