2012-08-04 74 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