为什么 Bitmap 会导致规则 CA2000,而 Image 不会?
有很多关于 SO 的问题感叹 VS2010 可能过于严格地应用代码分析规则 CA2000,但我似乎遇到了应该应用它的情况,但没有应用它。
考虑以下代码:
Image srcImage = Image.FromFile(source);
Bitmap newImage = new Bitmap(newWidth, newHeight);
using (Graphics gr = Graphics.FromImage(newImage))
{
gr.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight));
}
newImage.Save(destination, ImageFormat.Jpeg);
现在,如果我在 Visual Studio 2010 中对此运行代码分析,它会抱怨 newImage 没有被释放(很容易修复,将其放在另一个 using 块中),但它不会抱怨 srcImage (它还有一个我从未调用过的 Dispose() 方法)。有谁知道为什么代码分析在这里不抱怨?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
CA2000 和类似/相关的 CA2213 (DisposableFieldsShouldBeDispose) 和 CA1001 (TypesThatOwnDisposableFieldsShouldBeDisposable) 规则对于如何识别一次性的“所有权”相当严格。仅当使用实例构造函数直接在代码中创建实例时,他们才会将您的代码视为一次性实例的所有者。由于您使用 Image.FromFile 创建 srcImage 实例,因此该规则不会将您的代码识别为所有者。
如果您不同意此规则行为,您可能需要在 https://connect.microsoft 上创建错误报告。 com/visualstudio/feedback。 (如果您关心一次性字段规则,您可能需要投票支持现有的 https://connect.microsoft.com/VisualStudio/feedback/details/485291/typesthatowndisposablefieldsshouldbedisposable-rule-ca1001-is-too-permissive建议。)
CA2000 and the similar/related CA2213 (DisposableFieldsShouldBeDisposed) and CA1001 (TypesThatOwnDisposableFieldsShouldBeDisposable) rules are rather strict about how they recognize "ownership" of a disposable. They will only consider your code to be the owner of a disposable instance if an instance constructor is used to create the instance directly in your code. Since you use Image.FromFile to create the instance for srcImage, the rule doesn't recognize your code as the owner.
If you disagree with this rule behaviour, you may want to create a bug report at https://connect.microsoft.com/visualstudio/feedback. (If you care about the disposable field rules, you might want to vote for the existing https://connect.microsoft.com/VisualStudio/feedback/details/485291/typesthatowndisposablefieldsshouldbedisposable-rule-ca1001-is-too-permissive suggestion while you're at it.)
好吧,它也应该“抱怨 srcImage”,但是我猜测它不会抱怨它,因为您将其传递给
DrawImage
方法“gr. DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight));
", 所以要么它不够聪明,知道方法返回后它不会被用于更多操作,要么它假设那你在将被处置的gr
实例中使用它。无论如何,您应该对srcImage
使用using
,就像您对newImage
所做的那样,并且不要遵循代码分析。Well it should "complain about srcImage" too, however I guess that it doesn't complain about it because you are passing it to the
DrawImage
method "gr.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight));
", So either it is not smart enough to know that it will not being used for more actions after the method returned, or maybe it assumed that you used it ingr
instance that will be disposed. Anyway you should useusing
forsrcImage
just like what you are doing withnewImage
and don't follow the Code Analysis on that.