C# .NET 获取枚举值的自定义属性

2021-06-18 04:04

阅读:514

标签:typeof   div   strong   pac   summary   attribute   desc   extension   自定义属性   

一、定义一个类

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

namespace XXX.XXX.Utils
{
    /// 
    /// 备注特性
    /// 
    public class DescAttribute : Attribute
    {
        private string m_desc;
        public DescAttribute(string desc)
        {
            this.m_desc = desc;
        }
        /// 
        /// 备注
        /// 
        public string Desc
        {
            get { return m_desc; }
            set { m_desc = value; }
        }
        /// 
        /// 获取枚举的备注信息
        /// 
        /// 枚举值
        /// 
        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;
        }
    }
    /// 
    /// 枚举扩展类
    /// 
    public static class EnumExtension
    {
        /// 
        /// 获取枚举的备注信息
        /// 
        /// 
        /// 
        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 获取枚举值的自定义属性

标签:typeof   div   strong   pac   summary   attribute   desc   extension   自定义属性   

原文地址:https://www.cnblogs.com/fan-yuan/p/10316352.html


评论


亲,登录后才可以留言!