【问题标题】:Tell resharper that a Func<string> will never return null告诉 resharper Func<string> 永远不会返回 null
【发布时间】:2018-08-21 04:42:05
【问题描述】:
[NotNull]
private readonly Func<string> FunctionThatWillNeverBeNullNorReturnNull;
void Test(){
string thisStringIsNotNull = FunctionThatWillNeverBeNullNorReturnNull();
}
我如何告诉 resharper 上面的函数永远不会返回 null?放置 [NotNull] 意味着函数引用不能为空,但我不确定如何告诉 resharper 它返回的内容也不会为空。
【问题讨论】:
标签:
c#
null
resharper
code-analysis
static-analysis
【解决方案1】:
我所做的是创建一个可以注释的委托。
但是,ReSharper 不会显示返回值的警告。它仅适用于委托参数。
[CanBeNull]
public delegate string ReturnMaybeNull();
[NotNull]
public delegate string ReturnNotNull([NotNull]string someParam);
[NotNull]
private readonly ReturnMaybeNull FunctionThatMayReturnNull = () => null;
[NotNull]
private readonly ReturnNotNull FunctionThatNeverReturnsNull = someParam => null; // no warning
void Test()
{
bool test = FunctionThatMayReturnNull().Equals(""); // no warning
string thisStringIsNotNull = FunctionThatNeverReturnsNull(null); // parameter warning here
if (thisStringIsNotNull == null) // no warning
{
test = test ^ true;
}
}