在c#中将字符串转换为枚举值的最佳方法是什么?
我有一个包含枚举值的HTML选择标记。当页面被发布时,我想获取值(将以字符串的形式)并将其转换为相应的枚举值。
在理想的情况下,我可以这样做:
StatusEnum MyStatus = StatusEnum.Parse("Active");
但这不是有效的代码。
在c#中将字符串转换为枚举值的最佳方法是什么?
我有一个包含枚举值的HTML选择标记。当页面被发布时,我想获取值(将以字符串的形式)并将其转换为相应的枚举值。
在理想的情况下,我可以这样做:
StatusEnum MyStatus = StatusEnum.Parse("Active");
但这不是有效的代码。
当前回答
在某种程度上,还添加了Parse的通用版本。对我来说,这是可取的,因为我不需要“尝试”解析,我也希望结果内联而不生成输出变量。
ColorEnum color = Enum.Parse<ColorEnum>("blue");
MS文档:解析
其他回答
请注意:
enum Example
{
One = 1,
Two = 2,
Three = 3
}
Enum.(Try)Parse()接受多个逗号分隔的参数,并将它们与二进制'或' | '组合。你不能禁用这个,在我看来,你几乎从来都不想要它。
var x = Enum.Parse("One,Two"); // x is now Three
即使没有定义3,x仍然会得到int值3。更糟糕的是:枚举. parse()可以给你一个甚至没有为枚举定义的值!
我不想经历用户自愿或不情愿触发这种行为的后果。
此外,正如其他人所提到的,对于大型枚举(即可能值的数量呈线性),性能不太理想。
我的建议如下:
public static bool TryParse<T>(string value, out T result)
where T : struct
{
var cacheKey = "Enum_" + typeof(T).FullName;
// [Use MemoryCache to retrieve or create&store a dictionary for this enum, permanently or temporarily.
// [Implementation off-topic.]
var enumDictionary = CacheHelper.GetCacheItem(cacheKey, CreateEnumDictionary<T>, EnumCacheExpiration);
return enumDictionary.TryGetValue(value.Trim(), out result);
}
private static Dictionary<string, T> CreateEnumDictionary<T>()
{
return Enum.GetValues(typeof(T))
.Cast<T>()
.ToDictionary(value => value.ToString(), value => value, StringComparer.OrdinalIgnoreCase);
}
枚举。解析是你的朋友:
StatusEnum MyStatus = (StatusEnum)Enum.Parse(typeof(StatusEnum), "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
不确定什么时候添加的,但在Enum类上现在有一个
Parse<TEnum>(stringValue)
与问题中的例子一起用:
var MyStatus = Enum.Parse<StatusEnum >(“Active”)
或者忽略大小写:
var MyStatus = Enum.Parse<StatusEnum >(“active”, true)
下面是它使用的反编译方法:
[NullableContext(0)]
public static TEnum Parse<TEnum>([Nullable(1)] string value) where TEnum : struct
{
return Enum.Parse<TEnum>(value, false);
}
[NullableContext(0)]
public static TEnum Parse<TEnum>([Nullable(1)] string value, bool ignoreCase) where TEnum : struct
{
TEnum result;
Enum.TryParse<TEnum>(value, ignoreCase, true, out result);
return result;
}
使用TryParse的超级简单代码:
var value = "Active";
StatusEnum status;
if (!Enum.TryParse<StatusEnum>(value, out status))
status = StatusEnum.Unknown;