在 C# 中使用 switch 来处理所有配置单元

Using switch in C# to handle all hives

我试图使用 switch 来处理注册表中所有可能的配置单元 - 稍后,我想为作为输入提供的密钥(连同配置单元)生成 SubKeyNames,但我仍然收到如下错误: “一个名为‘regKey’的局部变量已在此范围内定义” “名称‘regKey’在当前上下文中不存在”

switch (hive) {  

    case "HKEY_CLASSES_ROOT":

                   RegistryKey regKey=Registry.ClassesRoot.OpenSubKey(key,false);
                   break;                                 

    case "HKEY_CURRENT_USER":

                   RegistryKey regKey=Registry.CurrentUser.OpenSubKey(key,false);
                   break;  

    case "HKEY_LOCAL_MACHINE":

                   RegistryKey regKey=Registry.LocalMachine.OpenSubKey(key,false);
                   break;

    case "HKEY_USERS":

                   RegistryKey regKey=Registry.Users.OpenSubKey(key,false);
                   break;  

    case "HKEY_CURRENT_CONFIG":

                   RegistryKey regKey=Registry.CurrentConfig.OpenSubKey(key,false);
                   break;  

    default:
        throw new System.Exception("Incorrent hive");
}

我认为错误是你试图在同一个程序中声明变量 multiply times 我会尝试将变量的创建移动到你的 switch 结构之外,然后在 switch 结构期间为其赋值

如果你想要case你可以尝试模式匹配(你需要c#8.0),例如

RegistryKey regKey = hive switch {
  "HKEY_CLASSES_ROOT"   => Registry.ClassesRoot.OpenSubKey(key, false),
  "HKEY_CURRENT_USER"   => Registry.CurrentUser.OpenSubKey(key, false),
  "HKEY_LOCAL_MACHINE"  => Registry.LocalMachine.OpenSubKey(key, false),
  "HKEY_USERS"          => Registry.Users.OpenSubKey(key, false),
  "HKEY_CURRENT_CONFIG" => Registry.CurrentConfig.OpenSubKey(key, false),
  _ => throw new NotSupportedException("Incorrent hive")
};

或者要摆脱讨厌的 Registry ... OpenSubKey(key, false),您可以将键移动到 Dictionary:

private static Dictionary<string, RegistryKey> s_RegRoots = 
  new Dictionary<string, RegistryKey>(StringComparer.OrdinalIgnoreCase) {
    {"HKEY_CLASSES_ROOT",   Registry.ClassesRoot},
    {"HKEY_CURRENT_USER",   Registry.CurrentUser},
    {"HKEY_LOCAL_MACHINE",  Registry.LocalMachine},
    {"HKEY_USERS",          Registry.Users},
    {"HKEY_CURRENT_CONFIG", Registry.CurrentConfig},
};

...


RegistryKey regKey = s_RegRoots.TryGetValue(hive, out var root)
  ? root.OpenSubKey(key, false)
  : throw new NotSupportedException("Incorrent hive");