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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1578775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:00:07  来源:igfitidea点击:

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

c#enums

提问by Luiz Costa

I have an enum:

我有一个枚举:

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

How can I, given the string HKEY_LOCAL_MACHINE, get a value 0x80000002based on the enum?

给定 string HKEY_LOCAL_MACHINE,我如何0x80000002根据枚举获取值?

采纳答案by Mehrdad Afshari

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 */ }

Before .NET 4.5, you had to do the following, which is more error-prone and throws an exception when an invalid string is passed:

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

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

回答by Joseph

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

回答by Frank Bollack

With some error handling...

通过一些错误处理...

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

回答by Nigel

Using Enum.TryParse you don't need the Exception handling:

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

baseKey e;

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

回答by George Findulov

Alternate solution can be:

替代解决方案可以是:

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

Or just:

要不就:

uint value = (uint)baseKey.HKEY_LOCAL_MACHINE;

回答by Rahul Bhat

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

This code snippet illustrates obtaining an enum value from a string. To convert from a string, you need to use the static Enum.Parse()method, which takes 3 parameters. The first is the type of enum you want to consider. The syntax is the keyword typeof()followed by the name of the enum class in brackets. The second parameter is the string to be converted, and the third parameter is a boolindicating whether you should ignore case while doing the conversion.

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

Finally, note that Enum.Parse()actually returns an object reference, that means you need to explicitly convert this to the required enum type(string,intetc).

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

Thank you.

谢谢你。