简体   繁体   中英

How do I return the enum value that matches a given string?

So I have a string and I want to get a value from an enum to return with the same name as string. Example:

enum Types{
    one,
    two,
    three
}

private Types getType(string value){   //Let's say value is "two"
    return Types.value;                //This should return the enum "two" of Types
}

I hope I made it clear enough!

使用Enum.Parse

var t = (Types)Enum.Parse(typeof(Types), "two");

If you're using .NET 4.0 or later, you can use the Enum.TryParse<TEnum> Method :

Types result;

if (Enum.TryParse<Types>("two", out result))
{
     // result == Types.two
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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