c# - 获取通用枚举的描述属性

标签 c# generics enums attributes

我在尝试使枚举通用时遇到了一些困难。我读到它不是那么简单,而且我似乎找不到解决方案。

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

这是我目前所拥有的:

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();
}

我目前遇到的问题是:

cannot convert from 'int' to 'System.Enum'

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

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

这是我遇到的错误:

cannot convert from 'T' to 'System.Enum'

最佳答案

在这里,试试这个:

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

关于c# - 获取通用枚举的描述属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36573176/

相关文章:

c# - 如何将一个部分传递给部分布局?

c# - asp.net向导控件不可点击侧边栏

java - 非通用子类继承(实现)通用父类(super class)(接口(interface))

Java map 要设置吗?有没有办法实现预先存在的java库以允许包含Sets作为值的Map?

java - 泛型删除和遗留代码

java - 如何拥有带有创建和更新日期的枚举查找表?

c# - 解析 C#,查找方法并将 try/catch 放入所有方法

C# JSON 反序列化 null 嵌套属性

swift - 在 for ... where 子句中测试枚举是否相等

c# - Console.WriteLine(Enum.Value) 在 C# 和 VB.Net 中给出不同的输出