在c#中将字符串转换为枚举值的最佳方法是什么?
我有一个包含枚举值的HTML选择标记。当页面被发布时,我想获取值(将以字符串的形式)并将其转换为相应的枚举值。
在理想的情况下,我可以这样做:
StatusEnum MyStatus = StatusEnum.Parse("Active");
但这不是有效的代码。
在c#中将字符串转换为枚举值的最佳方法是什么?
我有一个包含枚举值的HTML选择标记。当页面被发布时,我想获取值(将以字符串的形式)并将其转换为相应的枚举值。
在理想的情况下,我可以这样做:
StatusEnum MyStatus = StatusEnum.Parse("Active");
但这不是有效的代码。
当前回答
注意,enuml . parse()的性能并不理想,因为它是通过反射实现的。(枚举. tostring()也是如此,它是反过来的。)
如果你需要在性能敏感的代码中将字符串转换为枚举,最好的方法是在启动时创建Dictionary<String,YourEnum>,并使用它来进行转换。
其他回答
public TEnum ToEnum<TEnum>(this string value, TEnum defaultValue){
if (string.IsNullOrEmpty(value))
return defaultValue;
return Enum.Parse(typeof(TEnum), value, true);}
您正在寻找枚举。解析。
SomeEnum enum = (SomeEnum)Enum.Parse(typeof(SomeEnum), "EnumValue");
在。net 4.5中不使用try/catch和TryParse()方法将字符串解析为TEnum
/// <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;
}
首先,你需要装饰你的枚举,像这样:
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
我使用了class(具有解析和性能改进的Enum强类型版本)。我在GitHub上找到了它,它应该也适用于。net 3.5。它有一些内存开销,因为它缓冲了一个字典。
StatusEnum MyStatus = Enum<StatusEnum>.Parse("Active");
这篇博文是Enums - NET 3.5中更好的语法,更好的性能和TryParse。
和代码: https://github.com/damieng/DamienGKit/blob/master/CSharp/DamienG.Library/System/EnumT.cs