4

我有以下代码:

RegistryKey installKey = Registry.LocalMachine.OpenSubKey(installKey);

我在我的代码上运行一个静态分析工具,它给了我一个缺陷,说我从方法返回而没有处理installKey。我知道您可以在 .NET 4.0 或更高版本中调用 RegistryKey 上的 Dispose(),但我的代码在 .NET 3.5 上运行。

有人知道处置此 RegistryKey 并让我的静态分析工具满意的最佳方法吗?

4

2 回答 2

8

您应该将代码包装在一个using块中,这将隐式调用Dispose您。目前尚不清楚您使用的是什么静态分析工具,但希望它能理解using

using (RegistryKey installKey = Registry.LocalMachine.OpenSubKey(installKey))
{
    // Your code here
}

请注意,您也可以Dispose显式调用,但您需要先转换RegistryKeyIDisposable

((IDisposable)installKey).Dispose()
于 2012-03-28T09:51:13.167 回答
2

当然可以在 3.5 版本中处理!请参阅此处的文档。

使用using块,如此处的 MSDN 示例中所示或者像在任何其他 IDisposable 对象中一样简单地调用 Dispose()。

于 2012-03-28T09:50:27.147 回答