我有以下代码:
RegistryKey installKey = Registry.LocalMachine.OpenSubKey(installKey);
我正在我的代码上运行一个静态分析工具,它给了我一个缺陷,说我从medthod返回而没有释放installkey。我知道您可以在.net 4.0或更高版本中对registrykey调用dispose(),但我的代码运行在.net 3.5上。
有没有人知道处理这个registrykey并让我的静态分析工具保持愉快的最佳方法?
最佳答案
您应该将代码包装在一个using
块中,它将隐式地为您调用Dispose
。目前还不清楚您使用的是什么静态分析工具,但希望它能理解using
:
using (RegistryKey installKey = Registry.LocalMachine.OpenSubKey(installKey))
{
// Your code here
}
注意,您也可以显式调用
Dispose
,但您需要首先将RegistryKey
转换为IDisposable
:((IDisposable)installKey).Dispose()