我可以教ReSharper定制的空检查吗?

t3c*_*b0t 13 c# resharper

ReSharper很聪明,知道a string.Format需要一个非null format参数,所以当我简单地写时它就会警告我

_message = string.Format(messageFormat, args);
Run Code Online (Sandbox Code Playgroud)

哪里messageFormat确实可以为空.只要我为此变量添加条件:

if (!string.IsNullOrEmpty(messageFormat))
{
    _message = string.Format(messageFormat, args);
}
Run Code Online (Sandbox Code Playgroud)

警告消失了.不幸的是,当我使用扩展方法时它不会:

if (messageFormat.IsNotNullOrEmpty())
{
    _message = string.Format(messageFormat, args); // possible 'null' assignment warning
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:有没有办法 ReSharper我的扩展方法具有相同的含义!string.IsNullOrEmpty(messageFormat)

扩展名定义为:

public static bool IsNotNullOrEmpty([CanBeNull] this string value) => !IsNullOrEmpty(value);
Run Code Online (Sandbox Code Playgroud)

Luc*_*ski 12

就在这里.您需要使用ReSharper注释来指导ReSharper的分析.您已经在使用[CanBeNull]它们,因此它们已在您的项目中定义.

你会感兴趣的是ContractAnnotationAttribute:

使用契约注释可以定义给定输入的预期输出,换句话说,定义函数的引用类型和布尔参数之间的依赖关系及其返回值.契约注释的机制允许创建可以更容易和更安全的方式使用的API.

这是你如何使用它:

[ContractAnnotation("null => false")]
public static bool IsNotNullOrEmpty(this string value)
    => !string.IsNullOrEmpty(value);
Run Code Online (Sandbox Code Playgroud)

该参数是可能的输入(地图上null,notnull,true,false),以输出(null,notnull,canbenull,true,false,halt):

这是另一个例子:

[ContractAnnotation("foo: null => halt; bar: notnull => notnull")]
public string Frob(string foo, string bar)
Run Code Online (Sandbox Code Playgroud)

表示如果将赋值函数传递nullfoo参数,它将永远不会返回(或抛出异常),并保证null如果将非null值传递给它,它将不会返回bar.

该文档更详细地描述了语法.


这是没有属性的情况:

之前

添加后警告消失:

后