是否有一个 Visual Studio 插件可以在代码违反 IDisposable 模式时发出警告?

发布于 2024-10-07 20:10:49 字数 211 浏览 5 评论 0原文

我想知道是否有一个插件可以检测并创建一个警告(或错误),如果它检测到创建了一个从未被释放的 IDisposable 对象。

我浏览了 Resharper 的文档,但没有看到任何看起来像我想要的东西。

编辑 - 更具体地说,我应该说一个实现 IDisposable 的局部变量,但从未被处理过。

例如,Pen是在paint方法中创建的,但在绘制完成后不会被释放。

I was wondering if there was an addon that could detect and create a warning (or error) if it detects the creation of an IDisposable object that is never disposed.

I looked through Resharper's docs but didn't see anything that looked like what I was wanting.

edit - To be more specific, I should have said a Local variable that implements IDisposable, but is never Disposed.

For instance, a Pen is created in a paint method, but not disposed with after the drawing is done.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

复古式 2024-10-14 20:10:49

该功能已在 FxCop 中打开和关闭多次。它目前的状态又是开启的,至少对于VS2010自带的版本来说是这样。它在此代码上生成 CA2000

    protected override void OnPaint(PaintEventArgs e) {
        var pen = new Pen(Brushes.Black);
    }

警告 5 CA2000:
Microsoft.Reliability:在方法中
'Form1.OnPaint(PaintEventArgs)',调用
对象上的 System.IDisposable.Dispose
'pen' 在所有对它的引用之前
超出范围。

请注意,这个警告的可靠性并不高,这是一个很难解决的问题。

This has been turned on and off a few times in FxCop. Its current state is on again, at least for the version that comes with VS2010. It generates CA2000 on this code:

    protected override void OnPaint(PaintEventArgs e) {
        var pen = new Pen(Brushes.Black);
    }

Warning 5 CA2000 :
Microsoft.Reliability : In method
'Form1.OnPaint(PaintEventArgs)', call
System.IDisposable.Dispose on object
'pen' before all references to it are
out of scope.

Beware that the reliability of this warning isn't great, it is a difficult problem to solve.

扶醉桌前 2024-10-14 20:10:49

静态分析工具不太可能显示某个对象是否在任意程序中被处理过。我相信这实际上相当于解决停止问题。

It's incredibly unlikely that a static analysis tool would be capable of showing that an object is or is not ever disposed in an arbitrary program. I believe that this would be effectively equivalent to solving the Halting problem.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文