Enums 如何获取枚举值和描述的列表?
我有以下枚举:Enums 如何获取枚举值和描述的列表?,enums,Enums,我有以下枚举: public enum AlertSeverity { [Description("Informative")] Informative = 1, [Description("Low risk")] LowRisk = 2, [Description("Medium risk")] MediumRisk = 3, [Description("High ri
public enum AlertSeverity
{
[Description("Informative")]
Informative = 1,
[Description("Low risk")]
LowRisk = 2,
[Description("Medium risk")]
MediumRisk = 3,
[Description("High risk")]
HighRisk = 4,
Critical = 5
}
我想得到所有描述/名称和值的列表
,
所以我试过这样的方法:
public static List<KeyValuePair<string, int>> GetEnumValuesAndDescriptions<T>() where T : struct
{
var type = typeof(T);
if (!type.IsEnum)
throw new InvalidOperationException();
List<KeyValuePair<string, int>> lst = new List<KeyValuePair<string, int>>();
foreach (var field in type.GetFields())
{
var attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; // returns null ???
if (attribute != null)
lst.Add(new KeyValuePair<string, int>(attribute.Description, ((T)field.GetValue(null)).ToInt()));
else
lst.Add(new KeyValuePair<string, int>(field.Name, ((T)field.GetValue(null)).ToInt())); // throws exception: "Non-static field requires a target" ???
}
return lst;
}
public静态列表GetEnumValuesAndDescriptions(),其中T:struct
{
var类型=类型(T);
如果(!type.IsEnum)
抛出新的InvalidOperationException();
List lst=新列表();
foreach(type.GetFields()中的var字段)
{
var attribute=attribute.GetCustomAttribute(字段,typeof(DescriptionAttribute))作为DescriptionAttribute;//返回null???
if(属性!=null)
添加(新的KeyValuePair(attribute.Description,((T)field.GetValue(null)).ToInt());
其他的
lst.Add(newkeyValuePair(field.Name,((T)field.GetValue(null)).ToInt());//引发异常:“非静态字段需要目标”???
}
返回lst;
}
我不知道为什么,但属性var返回null,字段名抛出异常“非静态字段需要目标”这应该可以:
public static List<KeyValuePair<string, int>> GetEnumValuesAndDescriptions<T>()
{
Type enumType = typeof (T);
if (enumType.BaseType != typeof(Enum))
throw new ArgumentException("T is not System.Enum");
List<KeyValuePair<string, int>> enumValList = new List<KeyValuePair<string, int>>();
foreach (var e in Enum.GetValues(typeof(T)))
{
var fi = e.GetType().GetField(e.ToString());
var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
enumValList.Add(new KeyValuePair<string, int>((attributes.Length > 0) ? attributes[0].Description : e.ToString(), (int)e));
}
return enumValList;
}
公共静态列表GetEnumValuesAndDescriptions()
{
类型enumType=typeof(T);
if(enumType.BaseType!=typeof(Enum))
抛出新的ArgumentException(“T不是System.Enum”);
List enumValList=新列表();
foreach(Enum.GetValues中的变量e(typeof(T)))
{
var fi=e.GetType().GetField(e.ToString());
var attributes=(DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute),false);
添加(新的KeyValuePair((attributes.Length>0)?属性[0]。说明:e.ToString(),(int)e));
}
返回枚举列表;
}