我想要一个干净/紧凑的模式,它是异常安全的并且将正确处理 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/