And*_*iff 4 c# using using-statement
我想使用using语句,但如果它应该指向的对象不存在,则可能需要更改我“使用”的变量的值。
我想到了这样的事情(用于注册表访问和 32/64 窗口 - 尽管这是我当前的用例,但这是一个普遍问题):
using (var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\MS\Platform"))
{
if (key == null)
key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432Node\MS\Platform");
// use key
}
Run Code Online (Sandbox Code Playgroud)
上面的代码不能编译:
error CS1656: Cannot assign to 'key' because it is a 'using variable'
Run Code Online (Sandbox Code Playgroud)
我可以通过不使用using而是 try/catch/finally 和/或在使用之前测试注册表项是否存在来解决此问题。
有没有办法继续使用using,然后处理正确的对象?
只需if取出using:
var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\MS\Platform");
if (key == null)
key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432Node\MS\Platform");
//prob best to null check
if (key != null)
{
using (key)
{
// use key
}
}
Run Code Online (Sandbox Code Playgroud)
仅供参考并解释为什么可以这样做,using声明只是语法糖:
readonly IDisposable item;
try
{
}
finally
{
item.Dispose();
}
Run Code Online (Sandbox Code Playgroud)
因为它被标记为readonly这也解释了为什么你不能在 using 语句中分配给它。
也许空合并?
using (var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\MS\Platform") ?? Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432Node\MS\Platform"))
{
// use key
}
Run Code Online (Sandbox Code Playgroud)