获取描述属性的通用枚举 [英] Getting Description Attribute of a Generic Enum

查看:122
本文介绍了获取描述属性的通用枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试通过枚举进行通用化时遇到困难。我已经看到这并不简单,我似乎找不到解决方案。



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



这是我到目前为止:

  public static KeyValuePair< string,List&KeyValueDataItem>> ConvertEnumWithDescription< T>()
其中T:struct,IConvertible
{
if(!typeof(T).IsEnum)
{
throw new Exception给定T必须是枚举);
}

var enumType = typeof(T).ToString()。Split('。')。

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(枚举值)
{
FieldInfo fi = value.GetType()GetField(value.ToString());

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

if(attributes.Length> 0)
返回属性[0] .Description;

返回值.ToString();
}

我目前遇到的问题是:


无法从int转换为System.Enum


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

  Value = GetEnumDescription((T)(对象)Convert.ToInt32(X)); 

这是我遇到的错误:


不能从'T'转换为'System.Enum'



解决方案

这里,尝试这样:

  public static KeyValuePair< string,List&KeyValueDataItem>> ConvertEnumWithDescription&T;()其中T:struct,IConvertible 
{
if(!typeof(T).IsEnum)
{
throw new Exception(Type given T must be一个枚举);
}

var enumType = typeof(T).ToString()。Split('。')。
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 = typeof(T);
var name = Enum.GetNames(type).Where(f => f.Equals(value,StringComparison.CurrentCultureIgnoreCase))选择(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])。
}

根据: http://www.extensionmethod.net/csharp/enum/getenumdescription


I'm having some hard time with trying to be generic with enums. I've read that it's not that simple, and I can't seem to find a solution.

I'm trying to create a generic function, that for an enum type would return the description for each enum value. I want to keep it generic and not to duplicate this method for each enum type...

Here's what I have so far:

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

The issue I'm currently having is that:

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

When I'm trying to call the function GetEnumDescription. If I convert it to T:

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

This is the error I'm getting:

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

解决方案

Here, try this:

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

Based on: http://www.extensionmethod.net/csharp/enum/getenumdescription

这篇关于获取描述属性的通用枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆