从字符串获取字符串值枚举的枚举描述

时间:2016-09-13 19:00:27

标签: c# generics enums

我有一个EnumHelper类来为枚举和反向类型转换做一些值。我有一个将字符串转换为枚举值,一个用于获取枚举值的描述​​,并且无法将这两个放在一起使得您提供字符串和枚举类型并让它返回枚举值的描述​​。即。

给定下面的枚举,提供一个带有字符串"ScanItemBarcode"的静态方法(存储在数据库中)并返回"Scan Item Barcode"(枚举值的描述​​)。

public enum ItemValidationTypes
{
    [Description("Scan Item Barcode")]
    ScanItemBarcode,

    [Description("Scan Location/Container")]
    ScanLocationContainer,
}

我将代码转换为枚举值的代码:

public static T GetEnumFromString<T>(string enumStringValue)
    where T : struct, IConvertible
{
    Type enumType = typeof(T);
    if (!enumType.IsEnum)
    {
        throw new Exception("T must be an Enum type.");
    }

    T val;
    return Enum.TryParse<T>(enumStringValue,true,out val) ? val : default(T);
}

然后我的代码从枚举值中获取枚举描述:

public static string GetEnumDescription(Enum enumElement)
{
    FieldInfo fi = enumElement.GetType().GetField(enumElement.ToString());

    DescriptionAttribute[] attributes =
        (DescriptionAttribute[])fi.GetCustomAttributes(
        typeof(DescriptionAttribute),
        false);

    if (attributes != null &&
        attributes.Length > 0)
        return attributes[0].Description;
    else
        return enumElement.ToString();
}

最后,问题代码,我尝试将上面两个结合起来:

public static string GetEnumDescription<T>(string strEnumValue)
    where T : struct, IConvertible
{
    T enumElement = GetEnumFromString<T>(strEnumValue);
    return GetEnumDescription((Enum)enumElement);
}

尝试合并产生的错误是您can't convert type T to System.Enum

0 个答案:

没有答案