resharper custom pattern replacement with negative equality expression

对着背影说爱祢 提交于 2019-12-22 05:09:20

问题


I have a rule in resharper to find calls to Nullable.HasValue

T? foo; 
//...

if(foo.HasValue)
{}

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

if(foo != null)
{}

This works great, but when it encounters a negated .HasValue, the result is a little strange.

if(!foo.HasValue) {}

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

Then resharper wants me to simplify the statement to just if(foo == null)

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

The rule is defined as:

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

search pattern:
$nullable$.HasValue

replace pattern:
$nullable$ != null

('Format after replace' and 'Shorten references' are both checked)

Is there a way I can write this rule so ReSharper handles it intelligently? I tried making a second rule for !$nullable$.HasValue, but that causes both rules to match which makes tool-tip suggestions look confusing: replace with == null and replace with != null.


回答1:


If is not really mandatory you can give up on this rule because, according to this post:

"The compiler replaces null comparisons with a call to HasValue, so there is no real difference. Just do whichever is more readable/makes more sense to you and your colleagues."



来源:https://stackoverflow.com/questions/11657922/resharper-custom-pattern-replacement-with-negative-equality-expression

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!