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/45588292/

相关文章:

oop - 将Dart枚举放入类或包导出文件中

java - 处理必须子类化的单例

c# - Telegram bot - 向/启动命令添加唯一键

c# - 如何在C#中将类似$ 1,248.99的货币字符串转换为小数?

c# - MIcrosoft Bot Framework 上的 session Bot 可能吗?

c# - 为什么我必须在泛型类的静态方法调用上使用 <T>

java - 在带有泛型参数的泛型方法中使用 Spring RestTemplate

java - 覆盖具有通用返回类型的方法

sql - 在基于 SQL 的应用程序中 self 记录 "codes"的最佳方法是什么?

c# - 在 Visual Studio 中执行查询时出错