简体   繁体   English

如何从字符串输入中获取显示枚举值

[英]How to get Display Enum value from string input

How do I get the value of an enum through input? 如何通过输入获得枚举的值?

enum Planets
{
   Mercury = 0,
   Venus,
   Earth
}

I want something like when a user inputs a string for example I get the Enum integer Value of that input. 我想要一些用户输入字符串的例子,例如我得到该输入的Enum整数值。

UserInput: Mercury

Value: 0

I did something like this: 我做了这样的事情:

Console.WriteLine("Value: "+(Planets)UserInput);

and as you can guess it won't compile. 并且你可以猜测它不会编译。

var planet = (Planets)Enum.Parse(typeof(Planets), UserInput);
int planetNumber = (int)planet;

First, you have to cast your input string into an enum of your choice. 首先,您必须将输入字符串转换为您选择的枚举。 That can be done with Enum.Parse(Type, String) : 这可以使用Enum.Parse(Type, String)来完成:

Planets planet = Enum.Parse(typeof(Planets), "Mercury")

Then you need to get the numerical value from the enum, which is a simple cast to integer: 然后你需要从枚举中获取数值,这是一个简单的转换为整数:

int value = (int)planet;

Be careful with the first step: if the user inputs a string that is not valid, you'll get an exception which you'll have to handle. 小心第一步:如果用户输入的字符串无效,您将获得一个您必须处理的异常。 To avoid that you can use the Enum.TryParse() method which return a bool indicating the success of the action and pass the resulting enum as an out parameter. 为了避免这种情况,您可以使用Enum.TryParse()方法返回一个指示操作成功的bool,并将生成的枚举作为out参数传递。

Planets result;
bool success = Enum.TryParse<Planets>("Mars", true, out result);
if(success){
    Console.Write((int)result);
} else {
    Console.Write("no match");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM