【问题标题】:Resharper custom search pattern to warn IDisposable objectsResharper 自定义搜索模式以警告 IDisposable 对象
【发布时间】:2011-03-07 01:04:07
【问题描述】:

由于 resharper 仍然没有对实现 IDisposable 的对象发出任何警告,我想创建一些在 resharper 5.0 中可用的自定义搜索模式。

到目前为止,我有这个:

(不要介意我在模式中替换 cmets,我并不关心它,我只想在处理一次性对象时在代码中明确警告。)

- <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>

这处理变量声明的情况,例如

Bitmap myBitmap = GetBitmap();
private Bitmap _bitmap;

和 CTOR 调用,例如

var myBitmap = new Bitmap(...);

不支持的,是这样的:

var myBitmap = GetBitmap();

我找不到任何关于如何定义搜索模式的示例,该模式将查找“var”用法或方法返回类型,即 typeof IDisposable。

我确定有办法,但我找不到。

【问题讨论】:

    标签: c# .net resharper idisposable


    【解决方案1】:

    这些模式的问题在于,当您实际处置对象时,它们并没有消失,除非可能是 using 语句中的局部变量声明。它也不跟踪对象所有权,例如对于工厂方法和传递方法。所以我相信通过结构化模式来实现它几乎是无用的。

    无论如何,您可能需要两种模式进行局部变量检查,例如

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

    其中表达式和类型正在实现 IDisposable。

    【讨论】:

    • 当然,我明白这一点,但我想要的只是在首次声明一次性对象时发出警告。感谢您的查询,但它们似乎不起作用。如果我只使用 $expression$,它可以工作,但每次使用对象时都会发出警告,我只想在声明中发出警告。
    【解决方案2】:

    虽然这不能直接回答您的问题,但有多种运行时技术可以找到未处理的 IDisposables。 Here's one such technique.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-14
      • 1970-01-01
      • 2014-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-19
      相关资源
      最近更新 更多