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