码迷,mamicode.com
首页 > 其他好文 > 详细

获取自定义Attribute的Description

时间:2014-12-31 19:58:20      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:

自定义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

标签:

原文地址:http://www.cnblogs.com/xiguain/p/4196369.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!