ReSharper:空检查始终是错误警告

use*_*754 8 c# generics resharper

使用ReSharper 8.2我会收到一个警告("表达式始终为false")进行空值检查

public bool TryGetValue(TKey key, out TValue value)
{
  if (key == null)
Run Code Online (Sandbox Code Playgroud)

来自NHibernate NullableDictionary.为什么是这样?我试试的时候

class Test<T> where T : class
Run Code Online (Sandbox Code Playgroud)

然后我没有按预期得到对T变量进行空检查的警告.

编辑:为了方便起见,链接源的类签名是:

public class NullableDictionary<TKey, TValue> : IDictionary<TKey, TValue> where TKey : class
Run Code Online (Sandbox Code Playgroud)

Gra*_*ICA 9

它正在发生,因为这个类实现了IDictionary<TKey, TValue>; 如果您(暂时)删除类签名的接口部分,警告将消失.

由于标准System.Collections.Generic.Dictionary类中的"键" 永远不会null(它抛出ArgumentNullException),我会说ReSharper做出了错误的假设.


测试行为:

我在一个空的项目中测试了这个类并试了一下.尽管ReSharper使所有代码变灰,但它仍然在运行时仍然执行.

灰色文本表示ReSharper的认为逻辑将一直下降通过对else块,但是这显然并非如此,当你使用它.

在此输入图像描述


修复,使用注释:

为了解决ReSharper的问题,默认情况下假设密钥不可用null,您可以使用JetBrains Annotations.

添加对JetBrains Annotations程序集的引用.对我来说,这是位置:

C:\ Program Files(x86)\ JetBrains\ReSharper\v8.2\Bin\JetBrains.Annotations.dll

然后在类所在的文件顶部添加using指令:

using JetBrains.Annotations;
Run Code Online (Sandbox Code Playgroud)

现在使用CanBeNull属性标记该参数,您将看到ReSharper不再灰显文本:

public bool TryGetValue([CanBeNull] TKey key, out TValue value)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述