在c#中将字符串转换为枚举值的最佳方法是什么?
我有一个包含枚举值的HTML选择标记。当页面被发布时,我想获取值(将以字符串的形式)并将其转换为相应的枚举值。
在理想的情况下,我可以这样做:
StatusEnum MyStatus = StatusEnum.Parse("Active");
但这不是有效的代码。
在c#中将字符串转换为枚举值的最佳方法是什么?
我有一个包含枚举值的HTML选择标记。当页面被发布时,我想获取值(将以字符串的形式)并将其转换为相应的枚举值。
在理想的情况下,我可以这样做:
StatusEnum MyStatus = StatusEnum.Parse("Active");
但这不是有效的代码。
当前回答
首先,你需要装饰你的枚举,像这样:
public enum Store : short
{
[Description("Rio Big Store")]
Rio = 1
}
在。net 5中,我创建了这个扩展方法:
//The class also needs to be static, ok?
public static string GetDescription(this System.Enum enumValue)
{
FieldInfo fi = enumValue.GetType().GetField(enumValue.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0) return attributes[0].Description;
else return enumValue.ToString();
}
现在你有一个扩展方法可以在任何枚举中使用
是这样的:
var Desc = Store.Rio.GetDescription(); //Store is your Enum
其他回答
注意,enuml . parse()的性能并不理想,因为它是通过反射实现的。(枚举. tostring()也是如此,它是反过来的。)
如果你需要在性能敏感的代码中将字符串转换为枚举,最好的方法是在启动时创建Dictionary<String,YourEnum>,并使用它来进行转换。
// str.ToEnum<EnumType>()
T static ToEnum<T>(this string str)
{
return (T) Enum.Parse(typeof(T), str);
}
object Enum.Parse(System.Type enumType, string value, bool ignoreCase);
如果你有一个名为mood的enum,它会像这样:
enum Mood
{
Angry,
Happy,
Sad
}
// ...
Mood m = (Mood) Enum.Parse(typeof(Mood), "Happy", true);
Console.WriteLine("My mood is: {0}", m.ToString());
我们不能假设输入是完全有效的,于是就用了@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;
}
使用枚举。TryParse<T>(String, T)(≥.NET 4.0):
StatusEnum myStatus;
Enum.TryParse("Active", out myStatus);
使用c# 7.0的参数类型内联可以进一步简化:
Enum.TryParse("Active", out StatusEnum myStatus);