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);

 

posted @ 2013-09-30 13:54  JasonGu0  阅读(1797)  评论(0编辑  收藏  举报