今天需要一個對枚舉的反射,獲取值和名稱。
只需要這樣:
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 ""; } }
上面這種方式是集合了特性和反射的。