如何从C#中的字符串中获取枚举值?

Lui*_*sta 95 c# enums

我有一个枚举:

public enum baseKey : uint
{  
    HKEY_CLASSES_ROOT = 0x80000000,
    HKEY_CURRENT_USER = 0x80000001,
    HKEY_LOCAL_MACHINE = 0x80000002,
    HKEY_USERS = 0x80000003,
    HKEY_CURRENT_CONFIG = 0x80000005
}
Run Code Online (Sandbox Code Playgroud)

在给定字符串的情况下HKEY_LOCAL_MACHINE,如何0x80000002根据枚举获取值?

Meh*_*ari 166

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 */ }
Run Code Online (Sandbox Code Playgroud)

在.NET 4.5之前,您必须执行以下操作,这更容易出错,并在传递无效字符串时抛出异常:

(uint)Enum.Parse(typeof(baseKey), "HKEY_LOCAL_MACHINE")
Run Code Online (Sandbox Code Playgroud)

  • 现在有通用的Enum.TryParse <TEnum>()方法. (3认同)
  • 我总是想知道为什么 Enum.Parse 仍然没有通用重载。已经姗姗来迟了。 (2认同)

Nig*_*gel 27

使用Enum.TryParse,您不需要异常处理:

baseKey e;

if ( Enum.TryParse(s, out e) )
{
 ...
}
Run Code Online (Sandbox Code Playgroud)


Jos*_*eph 20

var value = (uint) Enum.Parse(typeof(baseKey), "HKEY_LOCAL_MACHINE");  
Run Code Online (Sandbox Code Playgroud)


Fra*_*ack 16

有一些错误处理......

uint key = 0;
string s = "HKEY_LOCAL_MACHINE";
try
{
   key = (uint)Enum.Parse(typeof(baseKey), s);
}
catch(ArgumentException)
{
   //unknown string or s is null
}
Run Code Online (Sandbox Code Playgroud)