简体   繁体   English

如何返回与给定字符串匹配的枚举值?

[英]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. 所以我有一个字符串,我希望从枚举中获取一个值,并返回与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 : 如果您使用的是.NET 4.0或更高版本,则可以使用Enum.TryParse <TEnum>方法

Types result;

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

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

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