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


102

我有一个枚举:

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基于枚举的值?

Answers:


173
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")

1
我总是想知道为什么Enum.Parse仍然没有泛型重载。早就该了。
Falanwe 2015年

3
现在有通用的Enum.TryParse <TEnum>()方法。
尤金·马克西莫夫

27

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

baseKey e;

if ( Enum.TryParse(s, out e) )
{
 ...
}

20
var value = (uint) Enum.Parse(typeof(baseKey), "HKEY_LOCAL_MACHINE");  

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
}

1
var value = (uint)Enum.Parse(typeof(basekey), "HKEY_LOCAL_MACHINE", true);

此代码段说明了从字符串获取枚举值。要从字符串转换,您需要使用静态Enum.Parse()方法,该方法需要3个参数。首先是您要考虑的枚举类型。语法是关键字,typeof()后跟方括号中的枚举类的名称。第二个参数是要转换的字符串,第三个参数bool指示在进行转换时是否应忽略大小写。

最后,需要注意的是Enum.Parse()实际返回一个对象的引用,你需要明确地将此转换为所需要的枚举类型(这意味着stringint等等)。

谢谢。


-2

替代解决方案可以是:

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

要不就:

uint value = (uint)baseKey.HKEY_LOCAL_MACHINE;

3
如何将字符串转换为枚举值?
Falanwe 2015年

枚举由两个部分组成:名称和值。假设名称为“ HKEY_LOCAL_MACHINE”,值为“ 0x80000002”。在这种情况下,Enum.Parse()方法是无用的,因为您可以将枚举成员转换为uint并获取值-2147483650。Enum.Parse()当然会产生相同的结果,但您可以硬编码字符串而不是参数直接使用您正在使用的枚举变量。
乔治·芬杜洛夫

4
您没有将字符串转换为"HKEY_LOCAL_MACHINE"值,而是按照OP的要求,将符号转换HKEY_LOCAL_MACHINE为值。野兽截然不同。
Falanwe 2015年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.