在c#中将字符串转换为枚举值的最佳方法是什么?

我有一个包含枚举值的HTML选择标记。当页面被发布时,我想获取值(将以字符串的形式)并将其转换为相应的枚举值。

在理想的情况下,我可以这样做:

StatusEnum MyStatus = StatusEnum.Parse("Active");

但这不是有效的代码。


当前回答

我开始使用这种方法。性能似乎还可以,但它需要一些样板代码设置。

public enum StatusType {
    Success,
    Pending,
    Rejected
}

static class StatusTypeMethods {

    public static StatusType GetEnum(string type) {
        switch (type) {
            case nameof(StatusType.Success): return StatusType.Success;
            case nameof(StatusType.Pending): return StatusType.Pending;
            case nameof(StatusType.Rejected): return StatusType.Rejected;
            default:
                throw new ArgumentOutOfRangeException(nameof(type), type, null);
        };
    }
}

之后,你可以这样使用它:

StatusType = StatusType.GetEnum("Success");

其他回答

// str.ToEnum<EnumType>()
T static ToEnum<T>(this string str) 
{ 
    return (T) Enum.Parse(typeof(T), str);
}

使用枚举。TryParse<T>(String, T)(≥.NET 4.0):

StatusEnum myStatus;
Enum.TryParse("Active", out myStatus);

使用c# 7.0的参数类型内联可以进一步简化:

Enum.TryParse("Active", out StatusEnum myStatus);

我们不能假设输入是完全有效的,于是就用了@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;
}

你必须使用Enum。解析从Enum中获取对象值,之后你必须将对象值更改为特定的Enum值。转换为enum值可以通过使用Convert.ChangeType来实现。请看下面的代码片段

public T ConvertStringValueToEnum<T>(string valueToParse){
    return Convert.ChangeType(Enum.Parse(typeof(T), valueToParse, true), typeof(T));
}

首先,你需要装饰你的枚举,像这样:

    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