在 C# 中将字符串转换为枚举
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16100/
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
Convert a string to an enum in C#
提问by Ben Mills
What's the best way to convert a string to an enumeration value in C#?
在 C# 中将字符串转换为枚举值的最佳方法是什么?
I have an HTML select tag containing the values of an enumeration. When the page is posted, I want to pick up the value (which will be in the form of a string) and convert it to the enumeration value.
我有一个包含枚举值的 HTML 选择标记。当页面发布时,我想获取值(它将采用字符串的形式)并将其转换为枚举值。
In an ideal world, I could do something like this:
在理想的世界中,我可以这样做:
StatusEnum MyStatus = StatusEnum.Parse("Active");
but that isn't a valid code.
但这不是有效的代码。
采纳答案by Keith
In .NET Core and .NET >4 there is a generic parse method:
在 .NET Core 和 .NET >4 中有一个通用的解析方法:
Enum.TryParse("Active", out StatusEnum myStatus);
This also includes C#7's new inline out
variables, so this does the try-parse, conversion to the explicit enum type and initialises+populates the myStatus
variable.
这也包括 C#7 的新内联out
变量,因此它会进行尝试解析、转换为显式枚举类型并初始化+填充myStatus
变量。
If you have access to C#7 and the latest .NET this is the best way.
如果您可以访问 C#7 和最新的 .NET,这是最好的方法。
Original Answer
原答案
In .NET it's rather ugly (until 4 or above):
在 .NET 中,它相当丑陋(直到 4 或更高版本):
StatusEnum MyStatus = (StatusEnum) Enum.Parse(typeof(StatusEnum), "Active", true);
I tend to simplify this with:
我倾向于用以下方法简化:
public static T ParseEnum<T>(string value)
{
return (T) Enum.Parse(typeof(T), value, true);
}
Then I can do:
然后我可以这样做:
StatusEnum MyStatus = EnumUtil.ParseEnum<StatusEnum>("Active");
One option suggested in the comments is to add an extension, which is simple enough:
评论中建议的一种选择是添加扩展名,这很简单:
public static T ToEnum<T>(this string value)
{
return (T) Enum.Parse(typeof(T), value, true);
}
StatusEnum MyStatus = "Active".ToEnum<StatusEnum>();
Finally, you may want to have a default enum to use if the string cannot be parsed:
最后,如果无法解析字符串,您可能希望使用默认枚举:
public static T ToEnum<T>(this string value, T defaultValue)
{
if (string.IsNullOrEmpty(value))
{
return defaultValue;
}
T result;
return Enum.TryParse<T>(value, true, out result) ? result : defaultValue;
}
Which makes this the call:
这使得这个电话:
StatusEnum MyStatus = "Active".ToEnum(StatusEnum.None);
However, I would be careful adding an extension method like this to string
as (without namespace control) it will appear on all instances of string
whether they hold an enum or not (so 1234.ToString().ToEnum(StatusEnum.None)
would be valid but nonsensical) . It's often be best to avoid cluttering Microsoft's core classes with extra methods that only apply in very specific contexts unless your entire development team has a very good understanding of what those extensions do.
但是,我会小心地将这样的扩展方法添加到string
as(没有名称空间控制)它将出现在所有实例上,string
无论它们是否持有枚举(因此1234.ToString().ToEnum(StatusEnum.None)
有效但无意义)。通常最好避免使用仅适用于非常特定上下文的额外方法来混淆 Microsoft 的核心类,除非您的整个开发团队非常了解这些扩展的作用。
回答by DavidWhitney
You're looking for Enum.Parse.
您正在寻找Enum.Parse。
SomeEnum enum = (SomeEnum)Enum.Parse(typeof(SomeEnum), "EnumValue");
回答by tags2k
Enum.Parseis your friend:
Enum.Parse是你的朋友:
StatusEnum MyStatus = (StatusEnum)Enum.Parse(typeof(StatusEnum), "Active");
回答by brendan
object Enum.Parse(System.Type enumType, string value, bool ignoreCase);
So if you had an enum named mood it would look like this:
所以如果你有一个名为情绪的枚举,它看起来像这样:
enum Mood
{
Angry,
Happy,
Sad
}
// ...
Mood m = (Mood) Enum.Parse(typeof(Mood), "Happy", true);
Console.WriteLine("My mood is: {0}", m.ToString());
回答by Mark Cidade
// str.ToEnum<EnumType>()
T static ToEnum<T>(this string str)
{
return (T) Enum.Parse(typeof(T), str);
}
回答by McKenzieG1
Note that the performance of Enum.Parse()
is awful, because it is implemented via reflection. (The same is true of Enum.ToString
, which goes the other way.)
请注意, 的性能Enum.Parse()
很糟糕,因为它是通过反射实现的。(同样适用于Enum.ToString
,反之亦然。)
If you need to convert strings to Enums in performance-sensitive code, your best bet is to create a Dictionary<String,YourEnum>
at startup and use that to do your conversions.
如果您需要在对性能敏感的代码中将字符串转换为枚举,最好的办法是Dictionary<String,YourEnum>
在启动时创建一个并使用它来进行转换。
回答by gap
We couldn't assume perfectly valid input, and went with this variation of @Keith's answer:
我们无法假设完全有效的输入,并采用了@Keith 答案的这种变体:
public static TEnum ParseEnum<TEnum>(string value) where TEnum : struct
{
TEnum tmp;
if (!Enum.TryParse<TEnum>(value, true, out tmp))
{
tmp = new TEnum();
}
return tmp;
}
回答by jite.gs
Parses string to TEnum without try/catch and without TryParse() method from .NET 4.5
将字符串解析为 TEnum,无需 try/catch 和来自 .NET 4.5 的 TryParse() 方法
/// <summary>
/// Parses string to TEnum without try/catch and .NET 4.5 TryParse()
/// </summary>
public static bool TryParseToEnum<TEnum>(string probablyEnumAsString_, out TEnum enumValue_) where TEnum : struct
{
enumValue_ = (TEnum)Enum.GetValues(typeof(TEnum)).GetValue(0);
if(!Enum.IsDefined(typeof(TEnum), probablyEnumAsString_))
return false;
enumValue_ = (TEnum) Enum.Parse(typeof(TEnum), probablyEnumAsString_);
return true;
}
回答by Erwin Mayer
Use Enum.TryParse<T>(String, T)
(≥ .NET 4.0):
使用Enum.TryParse<T>(String, T)
(≥ .NET 4.0):
StatusEnum myStatus;
Enum.TryParse("Active", out myStatus);
It can be simplified even further with C# 7.0's parameter type inlining:
可以使用 C# 7.0 的参数类型内联进一步简化:
Enum.TryParse("Active", out StatusEnum myStatus);
回答by Foyzul Karim
You can use extension methodsnow:
您现在可以使用扩展方法:
public static T ToEnum<T>(this string value, bool ignoreCase = true)
{
return (T) Enum.Parse(typeof (T), value, ignoreCase);
}
And you can call them by the below code (here, FilterType
is an enum type):
您可以通过以下代码调用它们(这里FilterType
是枚举类型):
FilterType filterType = type.ToEnum<FilterType>();