簡體   English   中英

如何從C#中的字符串中獲取枚舉值?

[英]How to get a enum value from string in C#?

我有一個枚舉:

public enum baseKey : uint
{  
    HKEY_CLASSES_ROOT = 0x80000000,
    HKEY_CURRENT_USER = 0x80000001,
    HKEY_LOCAL_MACHINE = 0x80000002,
    HKEY_USERS = 0x80000003,
    HKEY_CURRENT_CONFIG = 0x80000005
}

在給定字符串HKEY_LOCAL_MACHINE ,如何根據枚舉獲取值0x80000002

baseKey choice;
if (Enum.TryParse("HKEY_LOCAL_MACHINE", out choice)) {
     uint value = (uint)choice;

     // `value` is what you're looking for

} else { /* error: the string was not an enum member */ }

在.NET 4.5之前,您必須執行以下操作,這更容易出錯,並在傳遞無效字符串時拋出異常:

(uint)Enum.Parse(typeof(baseKey), "HKEY_LOCAL_MACHINE")

使用Enum.TryParse,您不需要異常處理:

baseKey e;

if ( Enum.TryParse(s, out e) )
{
 ...
}
var value = (uint) Enum.Parse(typeof(baseKey), "HKEY_LOCAL_MACHINE");  

有一些錯誤處理......

uint key = 0;
string s = "HKEY_LOCAL_MACHINE";
try
{
   key = (uint)Enum.Parse(typeof(baseKey), s);
}
catch(ArgumentException)
{
   //unknown string or s is null
}
var value = (uint)Enum.Parse(typeof(basekey), "HKEY_LOCAL_MACHINE", true);

此代碼段說明了從字符串中獲取枚舉值。 要從字符串轉換,您需要使用靜態Enum.Parse()方法,該方法需要3個參數。 第一個是您要考慮的枚舉類型。 語法是關鍵字typeof()后跟括號中枚舉類的名稱。 第二個參數是要轉換的字符串,第三個參數是bool指示在進行轉換時是否應忽略大小寫。

最后,請注意Enum.Parse()實際上返回一個對象引用,這意味着您需要將其顯式轉換為所需的枚舉類型( stringint等)。

謝謝。

替代解決方案可以是:

baseKey hKeyLocalMachine = baseKey.HKEY_LOCAL_MACHINE;
uint value = (uint)hKeyLocalMachine;

要不就:

uint value = (uint)baseKey.HKEY_LOCAL_MACHINE;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM