c# - CA2000 方法使用 "using",但不使用 try/finally

标签 c# .net code-analysis fxcop

我遇到了一个奇怪的情况,我想了解一下。这段代码给出了 CA2000 (在所有引用之前对对象调用 Dispose...):

var ms = new MemoryStream(Encoding.Default.GetBytes(DefaultControlTemplateXaml));
using(ms)
{
    var x = XamlReader.Load(ms);
    _defaultControlTemplate = x as ControlTemplate;
}

然而,这另一部分不是:

var ms = new MemoryStream(Encoding.Default.GetBytes(DefaultControlTemplateXaml));
try
{
    var x = XamlReader.Load(ms);
    _defaultControlTemplate = x as ControlTemplate;
}
finally { ms.Dispose(); }

根据 Microsoft's documentation :

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.

所以我真的在这里迷路了......这两个陈述不应该是相同的吗?

更新

因为人们坚持(没有阅读我的评论)解释 using 礼节。我会这样说:

  using (var ms = new MemoryStream(Encoding.Default.GetBytes(DefaultControlTemplateXaml)))
  {
    var x = XamlReader.Load(ms);
    _defaultControlTemplate = x as ControlTemplate;
  }

仍然在 fxcop 上给出了 CA2000,所以原来的问题仍然存在。

更新2

添加一些屏幕截图,以便您可以看到这是 Visual Studio 2010 和整个功能。

第一个版本(给出警告): With warning

第二个版本(好的): Correct build

最佳答案

(删除了一些不适用于问题的内容以及一些关于 ThreadAbortException 的不正确内容。)

您可能遇到了 CA2000 报告的误报。您可以搜索Microsoft Connect for CA2000 .存在很多问题(并非所有问题都是误报错误)。

由于这些误报,我个人在某些项目中关闭了 CA2000。我正在使用带有代码分析的 Visual Studio 2010,我刚刚验证了,是的,在不得不多次抑制 CA2000 之后,我们决定在我现在正在处理的项目中将其关闭。

关于c# - CA2000 方法使用 "using",但不使用 try/finally,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9738061/

相关文章:

c# - 如何初始化嵌套列表容量?

c# - 删除 taghelper 生成的输入标签中的前缀

c# - 在 .NET 中开发一个在后台运行的程序?

.net - 在 Visual Studio 中,我可以在调试时禁用我的应用程序签名吗?

c# - WPF - 为什么 ValidationRule 不是 DependencyObject?

algorithm - 该算法没有二次运行时间,对吗?

c# - Viewmodel 在需要之前实例化

c# - 在执行 select 子句之前检查列是否存在

c# - 禁用/修复 .Designer.cs 文件中的代码分析警告

algorithm - 关于快速排序 killer