这是测试用的代码,
private void button3_Click(object sender, EventArgs e) { foreach (var v in Enum.GetValues(typeof(AwardsType))) { object obj = FunEnum.GetCustomAttribute<AwardsType>((AwardsType)v); EnumDescription enumDes = obj as EnumDescription; if (enumDes != null) { Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + " DisplayText=" + enumDes.DisplayText + ", DisplayTextEx=" + enumDes.DisplayTextEx); } } foreach (var v in Enum.GetValues(typeof(AwardsType))) { object obj = FunEnum.GetCustomAttribute<AwardsType>((AwardsType)v); EnumDescription enumDes = obj as EnumDescription; if (enumDes != null) { Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + " DisplayText=" + enumDes.DisplayText + ", DisplayTextEx=" + enumDes.DisplayTextEx); } } }
以下为定义的类与静态函数
namespace WindowsFormsApplication1 { public enum AwardsType { [EnumDescription(DisplayText = "世界级", DisplayTextEx = "AA")] World = 1, [EnumDescription(DisplayText = "国家级", DisplayTextEx = "BB")] Country = 2, [EnumDescription(DisplayText = "省市级", DisplayTextEx = "CC")] Provinces = 3, [EnumDescription(DisplayText = "校级", DisplayTextEx = "DD")] School = 4, }; [AttributeUsage(AttributeTargets.Field | AttributeTargets.Enum)] public class EnumDescription : Attribute { public string DisplayText; public string DisplayTextEx; } public static class FunEnum { // 此处做一个dictionary,这样原则上每个enum只要反射一次就可以得到想要的值 static Dictionary<string, object> dictEnum = new Dictionary<string, object>(); public static object GetCustomAttribute<T>(T t) where T : struct { Type enumType = t.GetType(); if (!enumType.IsEnum) { return null; } string sKey = enumType.ToString() + "." + t.ToString(); if (!dictEnum.ContainsKey(sKey)) { FieldInfo[] infos = enumType.GetFields(); foreach (FieldInfo fi in infos) { string sTempKey = enumType.ToString() + "." + fi.GetValue(t); Debug.WriteLine("sTempKey= " + sTempKey); if (dictEnum.ContainsKey(sTempKey)) continue; object[] eds = fi.GetCustomAttributes(true); if (eds != null && eds.Length > 0) { dictEnum.Add(sTempKey, eds[0]); } else { dictEnum.Add(sTempKey, null); } } } if (dictEnum.ContainsKey(sKey)) { return dictEnum[sKey]; } else { return null; } } } }