在调用扩展方法之后,如何让resharper知道我的变量不为null?

Sam*_*der 7 c# resharper

我有一个扩展方法:

public static bool Exists(this object toCheck)
{
   return toCheck != null;
}
Run Code Online (Sandbox Code Playgroud)

如果我使用它然后做这样的事情:

if (duplicate.Exists())
    throw new Exception(duplicate);
Run Code Online (Sandbox Code Playgroud)

然后resharper警告我有一个可能的空引用异常.

我知道这是不可能的,但我怎么能告诉resharper这没关系呢?

Evk*_*Evk 4

您可以使用合同注释来完成此操作,但另一个答案中提供的方式对我不起作用(即 - 仍然会产生警告)。但这有效:

public static class Extensions {
    [ContractAnnotation("null => false; notnull => true")]
    public static bool Exists(this object toCheck) {
        return toCheck != null;
    }
}
Run Code Online (Sandbox Code Playgroud)

获取ContractAnnotationAttribute- 推荐的方法是安装JetBrains.Annotationsnuget 包。如果您不想安装软件包 - 转到 Resharper > 选项 > 代码注释并按“将实现复制到剪贴板”按钮,然后将其粘贴到项目中的任何位置(确保不更改命名空间)。