.NET 3.5 Dispose注册表项
我有以下代码:
RegistryKey installKey = Registry.LocalMachine.OpenSubKey(installKey);
我在我的代码上运行静态分析工具,它给了我一个缺陷,说我从方法返回而没有处理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
:
((IDisposable)installKey).Dispose()
当然它可以在3.5版本中处理! 请参阅此处的文档
使用using
块,如此处的MSDN示例,或者像在任何其他IDisposable对象中一样调用Dispose()。