C#:是否有一个干净的模式来找到与使用相结合的正确对象?

标签 c# registry using null-coalescing-operator

我想要一个干净/紧凑的模式,它是异常安全的并且将正确处理 rulesKey,即使有东西被抛出。使用 using 似乎不可能(除非可能有 4 个 using,但这看起来太冗长并且打开了我什至不需要打开的额外资源)。让我明白的是,这在 C++ 中会如此直接/容易。有好的解决办法吗?

{
    RegistryKey rulesKey = null;
    rulesKey = rulesKey ?? Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\Company\\Internal\\Product");
    rulesKey = rulesKey ?? Registry.LocalMachine.OpenSubKey("Software\\Company\\Company\\Internal\\Product");
    rulesKey = rulesKey ?? Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\Company\\Product");
    rulesKey = rulesKey ?? Registry.LocalMachine.OpenSubKey("Software\\Company\\Product");

    // Code using rulesKey, might throw

    rulesKey.Close();
}

最佳答案

你可以使用

using (RegistryKey rulesKey = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\Company\\Internal\\Product")
                                ?? Registry.LocalMachine.OpenSubKey("Software\\Company\\Company\\Internal\\Product")
                                ?? Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\Company\\Product")
                                ?? Registry.LocalMachine.OpenSubKey("Software\\Company\\Product"))
{
    //use rulesKey here
}

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. MSDN

关于C#:是否有一个干净的模式来找到与使用相结合的正确对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36780666/

相关文章:

.net - .NET 的 NewRelic 需要在注册表中将 COR_ENABLE_PROFILING 设置为 1

batch-file - 一行获取 Reg 查询的错误代码

java - 使用java代码关闭浏览器窗口

c# - .Net 和 C# 中的多态数值

windows - 是否可以通过 .bat/.cmd 脚本修改注册表项?

c++ - 在 C++ 中的 "using namespace::X"中的前导::是什么意思

namespaces - 我可以从 linqpad 查询中删除命名空间导入吗?

c# - 回滚一个非常具体的预览包,该包导致了一个肮脏的项目

c# - Visual Studio 2012 命令行编译器

c# - 如何验证 MVC 上的 RadioButton?