Resharper custom search pattern to warn IDisposable objects

倖福魔咒の 提交于 2019-11-28 06:16:12

问题


Since resharper still doesn't give out any warning regarding objects implementing IDisposable, I'd like to create some custom search patterns available in resharper 5.0.

So far I have this:

(And don't mind my replace comments in the patterns, I don't really care about it, I just want a clear warning in the code when dealing with disposable objects.)

- <CustomPatterns>
- <Pattern Severity="WARNING">
  <Comment>This class implements IDisposable interface.</Comment> 
  <ReplaceComment>Please use Using statement, or dispose the object manually when done using.</ReplaceComment> 
  <SearchPattern>$type$</SearchPattern> 
  <Params /> 
- <Placeholders>
  <IdentifierPlaceholder Name="var" Type="" ExactType="False" RegEx="" CaseSensitive="True" /> 
  <TypePlaceholder Name="type" Type="System.IDisposable" ExactType="False" /> 
  <ArgumentPlaceholder Name="args" Minimal="-1" Maximal="-1" /> 
  </Placeholders>
  </Pattern>
- <Pattern Severity="WARNING">
  <Comment>This class implements IDisposable interface.</Comment> 
  <ReplaceComment>Please use Using statement, or dispose the object manually when done using.</ReplaceComment> 
  <SearchPattern>new $type$($args$)</SearchPattern> 
  <Params /> 
- <Placeholders>
  <IdentifierPlaceholder Name="var" Type="" ExactType="False" RegEx="" CaseSensitive="True" /> 
  <TypePlaceholder Name="type" Type="System.IDisposable" ExactType="False" /> 
  <ArgumentPlaceholder Name="args" Minimal="-1" Maximal="-1" /> 
  </Placeholders>
  </Pattern>
  </CustomPatterns>

This handles cases of variable declaration, e.g.

Bitmap myBitmap = GetBitmap();
private Bitmap _bitmap;

and CTOR calls, e.g.

var myBitmap = new Bitmap(...);

What it doesn't support, is this:

var myBitmap = GetBitmap();

I can't find any example of how to define a search pattern that will either find 'var' usage, or a method return type, that is typeof IDisposable.

I'm sure there's a way, I can't find it though.


回答1:


The problem with these patterns is that they don't go away when you actually dispose the object, except may be for local variable declarations inside using statements. It also doesn't track object ownership, e.g. for factory methods and pass-through methods. So I believe making it through structured patterns is next to useless.

Anyway, you may need two patterns for local variable checks like

var $identifier$ = $expression$; 
$type$ $identifier$ = $expression$;

where expression and type are implementing IDisposable.




回答2:


While this doesn't directly answer your question, there are various runtime techniques to find undisposed IDisposables. Here's one such technique.



来源:https://stackoverflow.com/questions/3097145/resharper-custom-search-pattern-to-warn-idisposable-objects

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