2012-08-04 72 views
2

我试图找出枚举是如何工作的,我试图做一个函数来写入注册表,使用枚举的注册表的根,但也有点糊涂了解枚举

public enum RegistryLocation 
     { 
      ClassesRoot = Registry.ClassesRoot, 
      CurrentUser = Registry.CurrentUser, 
      LocalMachine = Registry.LocalMachine, 
      Users = Registry.Users, 
      CurrentConfig = Registry.CurrentConfig 
     } 

public void RegistryWrite(RegistryLocation location, string path, string keyname, string value) 
{ 
    // Here I want to do something like this, so it uses the value from the enum 
    RegistryKey key; 
    key = location.CreateSubKey(path); 
    // so that it basically sets Registry.CurrentConfig for example, or am i doing it wrong 
    .. 
} 

回答

5

问题是你试图使用类初始化枚举值,并使用枚举值作为类,这是你不能做的。从MSDN

经批准的类型枚举是字节,为sbyte,短,USHORT,INT,UINT 长或ulong。

你可以做的是将枚举作为标准枚举,然后根据枚举返回正确的RegistryKey。

例如:

public enum RegistryLocation 
    { 
     ClassesRoot, 
     CurrentUser, 
     LocalMachine, 
     Users, 
     CurrentConfig 
    } 

    public RegistryKey GetRegistryLocation(RegistryLocation location) 
    { 
     switch (location) 
     { 
      case RegistryLocation.ClassesRoot: 
       return Registry.ClassesRoot; 

      case RegistryLocation.CurrentUser: 
       return Registry.CurrentUser; 

      case RegistryLocation.LocalMachine: 
       return Registry.LocalMachine; 

      case RegistryLocation.Users: 
       return Registry.Users; 

      case RegistryLocation.CurrentConfig: 
       return Registry.CurrentConfig; 

      default: 
       return null; 

     } 
    } 

    public void RegistryWrite(RegistryLocation location, string path, string keyname, string value) { 
     RegistryKey key; 
     key = GetRegistryLocation(location).CreateSubKey(path); 
    } 
+0

HMH,我想我明白了,但究竟能在枚举中使用的=因为当时 – user1071461 2012-08-04 03:26:45

+1

你可以用它来非连续,数值分配给枚举。例如,如果你想让枚举从-1开始,然后从那里继续,你可以设置第一个条目= -1。例如:InvalidSelection = -1,NoSelection(值为0),ValidSelection(值为1)。 – 2012-08-04 03:31:23

+0

啊,明白了,谢谢你的信息 – user1071461 2012-08-04 09:54:06