我在尝试通用枚举方面遇到了一些困难。我读到事情没那么简单,我似乎找不到解决方案。
我正在尝试创建一个通用函数,对于枚举类型将返回每个枚举值的描述。我想保持它的通用性,而不是为每个枚举类型重复这个方法......
这是我到目前为止所拥有的:
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”
在这里,试试这个:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)