.NET 3.5处置注册表项 [英] .NET 3.5 Dispose Registry Key

查看:317
本文介绍了.NET 3.5处置注册表项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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

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

I am running a static analysis tool on my code and it is giving me a defect saying that I am returning from the medthod without disposing installKey. I know you can call Dispose() on RegistryKey in .NET 4.0 or later but my code runs on .NET 3.5.

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

Does anybody know the best way to Dispose this RegistryKey and keep my static analysis tool happy?

推荐答案

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

You should wrap your code within a using block, which will implicitly call Dispose for you . It's unclear what static analysis tool you're using, but hopefully it understands using:

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

请注意,您也可以显式调用Dispose,但是需要先将RegistryKey强制转换为IDisposable:

Note that you can also call Dispose explicitly, but you need to cast RegistryKey to IDisposable first:

((IDisposable)installKey).Dispose()

这篇关于.NET 3.5处置注册表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆