尽管有 ReSharper [NotNull] 注释,我是否应该添加显式空检查?

Should I add explicit null checks despite ReSharper [NotNull] annotations?

我正在使用 ReSharpers [NotNull] 这样的注释:

public void MyMethod([NotNull] string a)
{
    if(a == null) // Warning: Expression is always false.
    {
        throw new ArgumentNullException();
    }

    // ...
}

但是,由于 NotNull 注释,ReSharper 警告我未使用的前提条件检查,因为

expression is always false

但是,据我了解这些注释,它们仅表示参数永远不应该是null;也就是说,他们 不禁止 来电者传递 null,例如如

this.MyMethod(null);

甚至不太明显(更像是在真实代码中)

string foo = null;
this.MyMethod(foo);

因此我觉得 包含对 null 的先决条件检查是有意义的,但也许我错过了一个概念或不理解它正确。


使用 [NotNull] 注释参数包含显式可空性检查是否有意义?

我对此进行了测试,当用 [NotNull] 标记参数时,您基本上是在告诉该参数不应采用空字符串。传递空值时,您会收到来自 Resharper 的警告,告诉您 "Possible null assignment for entity marked with [NotNull] attribute.",但您没有收到错误,因此程序可以编译。 在被调用的方法中防止空值是明智的。