在调用扩展方法后,如何让 resharper 知道我的变量不为空?
How can I get resharper to know that my variable is not null after I have called an extension method on it?
我有一个扩展方法:
public static bool Exists(this object toCheck)
{
return toCheck != null;
}
如果我使用它然后做这样的事情:
if (duplicate.Exists())
throw new Exception(duplicate);
然后 resharper 警告我可能存在空引用异常。
我知道这是不可能的,但我如何告诉 resharper 这没问题?
您可以使用 "Contract Annotation Syntax" 向 Resharper 表明某个方法在某些情况下通常不会 return,例如当参数为空时。
对于您的示例,您可以这样做:
[ContractAnnotation(toCheck:notnull => true]
public static bool Exists(this object toCheck)
{
return toCheck != null;
}
其中 toCheck:null => true
告诉 Resharper 如果 toCheck
不为空,该方法将 return true
。
[编辑] 更新了 link 以指向最新的 Resharper 文档。
您可以使用合同注释来完成,但另一个答案中提供的方式对我不起作用(即 - 仍然会产生警告)。但是这个有效:
public static class Extensions {
[ContractAnnotation("null => false; notnull => true")]
public static bool Exists(this object toCheck) {
return toCheck != null;
}
}
要获得 ContractAnnotationAttribute
- 推荐的方法是安装 JetBrains.Annotations
nuget 包。如果您不想安装包 - 转到 Resharper > 选项 > 代码注释并按 "copy implementation to clipboard" 按钮,然后将其粘贴到项目中的任何位置(确保不更改命名空间)。
我有一个扩展方法:
public static bool Exists(this object toCheck)
{
return toCheck != null;
}
如果我使用它然后做这样的事情:
if (duplicate.Exists())
throw new Exception(duplicate);
然后 resharper 警告我可能存在空引用异常。
我知道这是不可能的,但我如何告诉 resharper 这没问题?
您可以使用 "Contract Annotation Syntax" 向 Resharper 表明某个方法在某些情况下通常不会 return,例如当参数为空时。
对于您的示例,您可以这样做:
[ContractAnnotation(toCheck:notnull => true]
public static bool Exists(this object toCheck)
{
return toCheck != null;
}
其中 toCheck:null => true
告诉 Resharper 如果 toCheck
不为空,该方法将 return true
。
[编辑] 更新了 link 以指向最新的 Resharper 文档。
您可以使用合同注释来完成,但另一个答案中提供的方式对我不起作用(即 - 仍然会产生警告)。但是这个有效:
public static class Extensions {
[ContractAnnotation("null => false; notnull => true")]
public static bool Exists(this object toCheck) {
return toCheck != null;
}
}
要获得 ContractAnnotationAttribute
- 推荐的方法是安装 JetBrains.Annotations
nuget 包。如果您不想安装包 - 转到 Resharper > 选项 > 代码注释并按 "copy implementation to clipboard" 按钮,然后将其粘贴到项目中的任何位置(确保不更改命名空间)。