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);
原文地址:https://www.cnblogs.com/jcdd-4041/p/3347168.html