首页 > 代码库 > 获取自定义Attribute的Description

获取自定义Attribute的Description

自定义Attribute

    /// <summary>    /// 合同状态    /// </summary>    public enum ContractStatus    {        [GlobalCode("新建")]        Pending = 0,        [GlobalCode("提交待审批")]        AuditPending = 3,        [GlobalCode("审批拒绝")]        AuditReject = 6    }    [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)]    public class GlobalCodeAttribute : DescriptionAttribute    {        public GlobalCodeAttribute(string _description)            : base(_description)        {        }    }

获取Enum的自定义Attribute

/// <summary>  /// 枚举帮助类  /// </summary>  public class EnumHelper{        /// <summary>          /// 获取枚举项的Attribute          /// </summary>          /// <typeparam name="T">自定义的Attribute</typeparam>          /// <param name="source">枚举</param>          /// <returns>返回枚举,否则返回null</returns>          public static T GetCustomAttribute<T>(Enum source) where T : Attribute        {            Type sourceType = source.GetType();            string sourceName = Enum.GetName(sourceType, source);            FieldInfo field = sourceType.GetField(sourceName);            object[] attributes = field.GetCustomAttributes(typeof (T), true);            foreach (object attribute in attributes)            {                if (attribute is T)                    return attribute as T;            }            return null;        }        /// <summary>          ///获取DescriptionAttribute描述          /// </summary>          /// <param name="source">枚举</param>          /// <returns>有description标记,返回标记描述,否则返回null</returns>          public static string GetDescription(Enum source)        {            var attr = GetCustomAttribute<System.ComponentModel.DescriptionAttribute>(source);            if (attr == null)                return null;            return attr.Description;        }}

执行

var status = ContractStatus.Pending;var globalCode = EnumHelper.GetDescription(status);System.Console.ReadKey();

输出结构:

>>新建

 

获取自定义Attribute的Description