1. 程式人生 > >C# .NET 獲取枚舉值的自定義屬性

C# .NET 獲取枚舉值的自定義屬性

null eric task har mar foreach param mcal 命名

一、定義一個類

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;

namespace XXX.XXX.Utils
{
    /// <summary>
    /// 備註特性
    /// </summary>
    public class DescAttribute : Attribute
    {
        private string m_desc;
        public DescAttribute(string desc)
        {
            this.m_desc = desc;
        }
        /// <summary>
        /// 備註
        /// </summary>
        public string Desc
        {
            get { return m_desc; }
            set { m_desc = value; }
        }
        /// <summary>
        /// 獲取枚舉的備註信息
        /// </summary>
        /// <param name="val">枚舉值</param>
        /// <returns></returns>
        public static string GetEnumDesc(Enum val)
        {
            Type type = val.GetType();
            FieldInfo fd = type.GetField(val.ToString());
            if (fd == null)
                return string.Empty;
            object[] attrs = fd.GetCustomAttributes(typeof(DescAttribute), false);
            string name = string.Empty;
            foreach (DescAttribute attr in attrs)
            {
                name = attr.Desc;
            }
            return name;
        }
    }
    /// <summary>
    /// 枚舉擴展類
    /// </summary>
    public static class EnumExtension
    {
        /// <summary>
        /// 獲取枚舉的備註信息
        /// </summary>
        /// <param name="em"></param>
        /// <returns></returns>
        public static string GetDesc(this Enum em)
        {
            Type type = em.GetType();
            FieldInfo fd = type.GetField(em.ToString());
            if (fd == null)
                return string.Empty;
            object[] attrs = fd.GetCustomAttributes(typeof(DescAttribute), false);
            string name = string.Empty;
            foreach (DescAttribute attr in attrs)
            {
                name = attr.Desc;
            }
            return name;
        }
    }
}

 

二、定義一個枚舉,並引用如上命名空間

public enum EnumCalculationTag
{
        [Desc("This is description")]
        A
}

  

三、獲取註解(需引用“一”中的命名空間)

EnumCalculationTag.A.GetDesc()

  

C# .NET 獲取枚舉值的自定義屬性