C#给枚举增加一个Attribute,并通过反射获取Attribute的值。(借鉴)
[AttributeUsage(AttributeTargets.Field)] public class EnumExtension : Attribute { private string title; public EnumExtension(string title) { this.title = title; } public static string Get(Type tp, string name) { MemberInfo[] mi = tp.GetMember(name); if (mi != null && mi.Length > 0) { EnumExtension attr = Attribute.GetCustomAttribute(mi[0], typeof(EnumExtension)) as EnumExtension; if (attr != null) { return attr.title; } } return null; } public static string Get(object enm) { if (enm != null) { MemberInfo[] mi = enm.GetType().GetMember(enm.ToString()); if (mi != null && mi.Length > 0) { EnumExtension attr = Attribute.GetCustomAttribute(mi[0], typeof(EnumExtension)) as EnumExtension; if (attr != null) { return attr.title; } } } return null; } } public enum BorderStyle { [EnumExtension("正常")] None, [EnumExtension("圆角")] Rounded }
使用以下的方法就能取得枚举的Attribute值:
string name = EnumExtension.Get(BorderStyle.Rounded);