【问题标题】:Why is resharper suggesting that the left operand is never null为什么 resharper 建议左操作数永远不会为空
【发布时间】:2014-11-13 08:51:33
【问题描述】:

似乎对话框结果返回一个可为空的布尔值 (bool?),因此无论何时使用返回对话框,您都应该注意 null 选项(我还在等着看发生.. .).

上面的代码(VS2012,Resharper 8)表明左操作数永远不会为空。任何想法为什么?

bool? dlg_result = some_window.ShowDialog();
bool some_bool = !dlg_result ?? true; // Resharper suggests this won't happen.

这是一个截图,更容易看:

编辑:
我查看了 resharper 文件,从 CommonDialogControl 使用它时,ShowDialog 似乎不会为空,但从 Window 使用它时它可能为空。附上截图。
似乎必须更深入地挖掘,因为我不确定我使用的是哪一个。

【问题讨论】:

  • 好吧,你可以看看这个答案,看看 ShowDialog 返回 null 的情况是非常具体的。在这种情况下,我会说它不会发生:stackoverflow.com/questions/990109/…
  • @SonerGönül 好吧,bool? :)
  • @RaphaëlAlthaus 为链接欢呼。我将把它与“修复”resharper 注释结合使用,看看发生了什么。

标签: c# visual-studio-2012 resharper


【解决方案1】:

ReSharper 包含一个名为 Code Annotations 的功能,它提供了一种机制,用于通过 ReSharper 的提示来装饰源代码。例如:

[NotNull]
public object Foo()
{
    return null; // Warning: Possible 'null' assignment
}      

NotNull 属性将指示 ReSharper 在尝试返回 null 时在方法中发出 Visual Studio 警告。它还会导致 ReSharper 发出建议,即不需要空合并运算符 (??),因为方法返回值永远不会为空:

Foo() ?? new object; //Causes '??' left operand is never null suggestion

ReSharper 还支持将 External Annotations 添加到核心 .Net 代码。这允许将这些提示添加到 ReSharper 无法控制的代码中。 (如果您想向 3rd 方库添加注释,也可以使用它)。

总而言之,ReSharper 似乎已将 Window.ShowDialog 注释为 [NotNull],因此即使返回类型可以为空,ReSharper“知道”它永远不会为空并提出您所看到的建议。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-09
  • 1970-01-01
  • 2015-12-06
  • 1970-01-01
相关资源
最近更新 更多