利用特性反射获取额外标注的信息

需求:我们想得到枚举上面的注释

1)枚举类

public enum Sex
    {
        /// <summary>
        ////// </summary>
        [CommonAttribute("")]
        Woman = 0,

        /// <summary>
        ////// </summary>
        [CommonAttribute("")]
        Man = 1,

        /// <summary>
        /// 其他
        /// </summary>
        [CommonAttribute("其他")]
        Other = 2
    }

2.特性类

public class CommonAttribute:Attribute
    {
        public string Remark { get; private set; }

        public CommonAttribute(string remark)
        {
            this.Remark = remark;
        }
    }

3.反射类(这里要引用反射 using System.Reflection;)

public class AttributeExtend
    {
        public static string GetRemark(Sex value)
        {
            Type type = value.GetType();
            var field = type.GetField(value.ToString());
            if (field.IsDefined(typeof(CommonAttribute), true))
            {
                CommonAttribute attribute = (CommonAttribute)field.GetCustomAttribute(typeof(CommonAttribute), true);
                return attribute.Remark;
            }
            else
            {
                return value.ToString();
            }
        }
    }

4.使用

static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Start");
                Console.WriteLine(AttributeExtend.GetRemark(Sex.Man));
                Console.WriteLine(AttributeExtend.GetRemark(Sex.Woman));
                Console.WriteLine(AttributeExtend.GetRemark(Sex.Other));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();
        }

5.补充扩展方法

1)修改反射类

public static class AttributeExtend
    {
        public static string GetRemark(this Enum value)
        {
            Type type = value.GetType();
            var field = type.GetField(value.ToString());
            if (field.IsDefined(typeof(CommonAttribute), true))
            {
                CommonAttribute attribute = (CommonAttribute)field.GetCustomAttribute(typeof(CommonAttribute), true);
                return attribute.Remark;
            }
            else
            {
                return value.ToString();
            }
        }
    }

2)使用

static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Start");
                Console.WriteLine(Sex.Man.GetRemark());
                Console.WriteLine(Sex.Woman.GetRemark());
                Console.WriteLine(Sex.Other.GetRemark());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();
        }

 

posted @ 2022-11-26 14:36  蜗牛的礼物  阅读(19)  评论(0编辑  收藏  举报