C# 获取枚举类的自定义Attribute

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

namespace demo
{
    /// 
    /// 枚举类
    /// 
    public enum TypeEnum
    {
        [EnumText("活跃型")]
        Active = 1,

        [EnumText("健康型")]
        Healthy = 2,

        [EnumText("稳健型")]
        Steady = 3
    }
    /// 
    /// 自定义Attribute
    /// 
    public class EnumText : Attribute
    {
        public EnumText(String text)
        {
            this.Text = text;
        }

        public String Text { get; set; }
    }
    /// 
    /// 帮助类
    /// 
    public class EnumHelper
    {
        /// 
        /// 获取自定义attribute 
        /// 
        /// 
        /// 
        /// 
        public static T GetAttribute(Enum enumObj)where T:Attribute
        {
            Type type = enumObj.GetType();
            Attribute attr = null;
            try
            {
                String enumName = Enum.GetName(type, enumObj);  //获取对应的枚举名
                FieldInfo field = type.GetField(enumName);  
                attr = field.GetCustomAttribute(typeof(T), false);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
         //       throw ex;
            }
            
            return (T)attr;
        }
        
        /// 
        /// 
        /// 
        /// 
        public static void Main(String[] args)
        {
            var enum1 = TypeEnum.Active;
            Console.WriteLine(GetAttribute(enum1).Text);

            Console.WriteLine("输入任意键结束");
            Console.ReadKey();
            
        }
    }
}

测试结果:

C# 获取枚举类的自定义Attribute_第1张图片

你可能感兴趣的:(C#,C#,Attribute)