C# 給列舉型別增加一個備註特性

韓天偉發表於2013-07-15
    /// <summary>
    /// 備註特性
    /// </summary>
    public class RemarkAttribute : Attribute
    {
        /// <summary>
        /// 備註
        /// </summary>
        public string Remark { get; set; }

        public RemarkAttribute(string remark)
        {
            this.Remark = remark;
        }
    }
    /// <summary>
    /// 列舉擴充套件類
    /// </summary>
    public static class EnumExtension
    {
        /// <summary>
        /// 獲取列舉的備註資訊
        /// </summary>
        /// <param name="em"></param>
        /// <returns></returns>
        public static string GetRemark(this Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            if (fi == null)
            {
                return value.ToString();
            }
            object[] attributes = fi.GetCustomAttributes(typeof(RemarkAttribute), false);
            if (attributes.Length > 0)
            {
                return ((RemarkAttribute)attributes[0]).Remark;
            }
            else
            {
                return value.ToString();
            }
        }

        public static string GetEnumDescription(this Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (attributes.Length > 0)
            {
                return attributes[0].Description;
            }
            else
            {
                return value.ToString();
            }
        }
    }
            var aaa = UserType.Type1.GetRemark();

            var aab = UserType.Type2.GetEnumDescription();

 

相關文章