获取泛型枚举的描述属性

3

我在尝试使用枚举类型时遇到了一些困难。我已经阅读了相关资料并知道这并不简单,但是我似乎找不到解决方法。

我正在尝试创建一个通用函数,针对枚举类型将返回每个枚举值的描述。我希望保持通用性,而不是为每个枚举类型重复此方法...

以下是我目前的代码:

public static KeyValuePair<string, List<KeyValueDataItem>> ConvertEnumWithDescription<T>()
    where T : struct, IConvertible
{
    if (!typeof(T).IsEnum)
    {
        throw new Exception("Type given T must be an Enum");
    }

    var enumType = typeof(T).ToString().Split('.').Last();

    var itemsList = Enum.GetValues(typeof(T))
            .Cast<T>()
            .Select(x => new KeyValueDataItem
            {
                Key = Convert.ToInt32(x),
                Value = GetEnumDescription(Convert.ToInt32(x))
            })
            .ToList();

    var res = new KeyValuePair<string, List<KeyValueDataItem>>(enumType, itemsList);

    return res;
}

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

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

    if (attributes.Length > 0)
        return attributes[0].Description;

    return value.ToString();
}

我目前遇到的问题是:

无法将“int”转换为“System.Enum”

当我尝试调用函数GetEnumDescription时。 如果我将它转换为T

Value = GetEnumDescription((T)(object)Convert.ToInt32(x));

这是我收到的错误信息:

无法将't'转换为'system.enum'

3个回答

3

这里,试一下这个:

public static KeyValuePair<string, List<KeyValueDataItem>> ConvertEnumWithDescription<T>() where T : struct, IConvertible
    {
        if (!typeof(T).IsEnum)
        {
            throw new Exception("Type given T must be an Enum");
        }

        var enumType = typeof(T).ToString().Split('.').Last();
        var itemsList = Enum.GetValues(typeof(T))
              .Cast<T>()
               .Select(x => new KeyValueDataItem
               {
                   Key = Convert.ToInt32(x),
                   Value = GetEnumDescription<T>(x.ToString())
               })
               .ToList();

        var res = new KeyValuePair<string, List<KeyValueDataItem>>(
            enumType, itemsList);
        return res;

    }

    public static string GetEnumDescription<T>(string value)
    {
        Type type = typeof(T);
        var name = Enum.GetNames(type).Where(f => f.Equals(value, StringComparison.CurrentCultureIgnoreCase)).Select(d => d).FirstOrDefault();

        if (name == null)
        {
            return string.Empty;
        }
        var field = type.GetField(name);
        var customAttribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
        return customAttribute.Length > 0 ? ((DescriptionAttribute)customAttribute[0]).Description : name;
}

参考:http://www.extensionmethod.net/csharp/enum/getenumdescription


1

我已经自行修改了一些代码部分,例如将返回类型更改为更符合C#标准API的返回值。

您可以在这里观看它运行。

public static EnumDescription ConvertEnumWithDescription<T>() where T : struct, IConvertible
{
    if (!typeof(T).IsEnum)
    {
        throw new ArgumentException("Type given T must be an Enum");
    }

    var enumType = typeof(T).Name;
    var valueDescriptions = Enum.GetValues(typeof (T))
        .Cast<Enum>()
        .ToDictionary(Convert.ToInt32, GetEnumDescription);

    return new EnumDescription
    {
        Type = enumType,
        ValueDescriptions = valueDescriptions
    };

}

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

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

    if (attributes.Length > 0)
        return attributes[0].Description;
    return value.ToString();
}

public class EnumDescription
{
    public string Type { get; set; }
    public IDictionary<int, string> ValueDescriptions { get; set; }
}

0

稍微修改了您的代码,将一个类型传递给描述方法,并将参数作为字符串值传递。然后将其转换回相应的枚举类型并检查其描述。

public static KeyValuePair<string, List<KeyValueDataItem>> ConvertEnumWithDescription<T>() where T : struct, IConvertible
{
        if (!typeof(T).IsEnum)
        {
            throw new Exception("Type given T must be an Enum");
        }

        var enumType = typeof(T).ToString().Split('.').Last();
        var type = typeof(T);

        var itemsList = Enum.GetValues(typeof(T))
                .Cast<T>()
                .Select(x => new KeyValueDataItem
                {
                    Key = Convert.ToInt32(x),
                    Value = GetEnumDescription<T>(Enum.GetName(typeof(T), x))
                })
                .ToList();

        var res = new KeyValuePair<string, List<KeyValueDataItem>>(
            enumType, itemsList);
        return res;

}       

public static string GetEnumDescription<T>(string enumValue)
{
    var value = Enum.Parse(typeof(T), enumValue);
    FieldInfo fi = value.GetType().GetField(value.ToString());

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

    if (attributes.Length > 0)
        return attributes[0].Description;
    return value.ToString();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接