我在尝试使用枚举类型时遇到了一些困难。我已经阅读了相关资料并知道这并不简单,但是我似乎找不到解决方法。
我正在尝试创建一个通用函数,针对枚举类型将返回每个枚举值的描述。我希望保持通用性,而不是为每个枚举类型重复此方法...
以下是我目前的代码:
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'