【问题标题】:resharper custom pattern replacement with negative equality expressionresharper 用负等式表达式替换自定义模式
【发布时间】:2012-07-25 20:16:29
【问题描述】:

我在 resharper 中有一个规则来查找对 Nullable.HasValue 的调用

T? foo; 
//...

if(foo.HasValue)
{}

//And it offers to replace with a comparison directly with null:

if(foo != null)
{}

这个很好用,但是遇到否定的.HasValue,结果就有点奇怪了。

if(!foo.HasValue) {}

//is replaced with
if(!(foo != null)) {}

然后 resharper 想让我将语句简化为 if(foo == null)

//ideally it would automatically get to this without the extra step:
if(foo == null) {}

规则定义为:

type:     System.ValueType or derived
nullable: expression of type System.Nullable<$type$>

search pattern:
$nullable$.HasValue

replace pattern:
$nullable$ != null

('替换后的格式'和'短引用'都被选中)

有没有办法可以编写此规则,以便 ReSharper 智能地处理它?我尝试为!$nullable$.HasValue 制定第二条规则,但这会导致两条规则匹配,从而使工具提示建议看起来令人困惑:replace with == nullreplace with != null

【问题讨论】:

  • 我不知道解决方案。只是一个想法,我猜你已经想到了:删除!foo.HasValue 的模式并只添加foo.HasValue!(foo != null) 的模式。因此,一次只有一个规则,但不幸的是,您需要对 !foo.HasValue 之类的代码使用 两个 连续模式。
  • 搜索模式仅包含肯定规则。我已经错过了好几次定义否定规则以排除模式的特殊代码的可能性。
  • Resharper 自定义模式很难解决,我希望有一个测试自定义模式引擎,你可以在里面运行一些已知的好和已知的坏表达式

标签: c# resharper


【解决方案1】:

如果不是真的强制你可以放弃这条规则,因为根据post

“编译器将 null 比较替换为对 HasValue 的调用,因此没有真正的区别。只要对您和您的同事更具可读性/更有意义。”

【讨论】:

  • 明白,但我的动机是我认为 null 比较更具可读性,我希望 resharper 强制执行该样式决定。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-14
  • 2012-02-12
  • 2016-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多