C#、锐化器"Possible 'null' assignment to entity"不应该警告



我有一个方法来转换字符串。IsNullOrWhiteSpace(字符串值)转化为一个扩展方法。

public static bool IsNullOrWhitespace(this string source)
{
  return string.IsNullOrWhiteSpace(source);
}

在我使用这个来检查null之后,Resharper仍然警告我作为[NotNull]参数传递的变量可能是null。

"Possible 'null' assignment to entity marked with 'NotNull' attribute"

如果我用原来的(string.IsNullOrWhiteSpace(str))替换我的使用(str. isnullorwhitespace()),警告不会显示。

是否有一种方法与Resharper,我可以训练它知道我的扩展方法是一个有效的空检查器,使这个空赋值警告不显示?

注意:

  1. 我不想用//resharper disable注释隐藏它。
  2. 我不想完全禁用它,因为它应该显示当我没有null检查。
编辑:

在JetBrains中有一个属性。NuGet包叫做ContractAnnotation,它可以完成这个任务。

[ContractAnnotation("source:null => true")]
public static bool IsNullOrWhitespace(this string source)
{
    return string.IsNullOrWhiteSpace(source);
}

找到了!

在JetBrains中有一个属性。NuGet包叫做ContractAnnotation,它可以完成这个任务。

[ContractAnnotation("source:null => true")]
public static bool IsNullOrWhitespace(this string source)
{
    return string.IsNullOrWhiteSpace(source);
}

除非,如果您想删除警告(ReSharper v2016.2),它应该是false而不是true,如答案所示。

[ContractAnnotation("parameterName:null => false")]
不是

[ContractAnnotation("parameterName:null => true")]

这是因为你仍然可以调用

((string)null).IsNullOrWhiteSpace()

和Resharper。

重写如下代码:

(source == null) || string.IsNullOrWhiteSpace(source)

也许它会停止抱怨