c# 对枚举的反射
今天需要一个对枚举的反射,获取值和名称。
只需要这样:
foreach (var item in Enum.GetValues(typeof(SignalFormat))) { Console.WriteLine(Convert.ToInt32(item) + "---->" + item.ToString()); }
item就是名称,将名称转换成int就是值。
还有一种方式
public static class AttributeHelper { public static string GetCustomAttributeValue(this DistributeTaskState em) { Type tp = em.GetType(); object obj = Activator.CreateInstance(tp); List<string> list = new List<string>(); foreach (var item in tp.GetFields()) { if (item.IsDefined(typeof(RemarkAttribute), true)) { RemarkAttribute remarkAttribute = (RemarkAttribute)item.GetCustomAttribute(typeof(RemarkAttribute), true); string val = item.GetRawConstantValue().ToString();//值 string name = item.Name;//字段(键) string v = item.ToString(); list.Add(remarkAttribute.GetRemark()); return remarkAttribute.GetRemark(); } } return ""; } }
上面这种方式是集合了特性和反射的。