zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C# 获取类、方法、属性的自定义特性(Attribute)信息

c#属性方法 获取 信息 自定义 特性 attribute
2023-09-14 09:12:33 时间

原文网址:https://www.cnblogs.com/Insist-Y/p/15319212.html

首先定义一个自定义的属性类MyAttribute,该类需要继承Attribute

复制代码
复制代码
    public class MyAttribute : Attribute
    {
        /// <summary>
        /// 代码
        /// </summary>
        public string Code { get; set; }

        /// <summary>
        /// 描述
        /// </summary>
        public string Msg { get; set; }

        public MyAttribute() { }

        public MyAttribute(string code,string msg)
        {
            this.Code = code;
            this.Msg = msg;
        }
    }
复制代码
复制代码

接下来定义一个使用MyAttribute的类AttributeTest

复制代码
复制代码
    [MyAttribute("C01","类属性描述")]
    public class AttributeTest
    {
        [My("C02","属性描述")] // 等价于      [MyAttribute("C02","属性描述")]
        public string Field { get; set; }

        [My("C03", "方法描述")]
        public void Method()
        {

        }
    }
复制代码
复制代码

测试读取AttributeTest的MyAttribute特性信息,代码如下:

复制代码
复制代码
        static void Main(string[] args)
        {
            // 获取类的属性描述
            var classIfno = typeof(AttributeTest).GetCustomAttribute<MyAttribute>();

            // 获取指定属性的属性描述
            var fieldIfno = typeof(AttributeTest).GetProperty("Field").GetCustomAttribute<MyAttribute>();

            // 获取指定方法的属性描述
            var methodIfno = typeof(AttributeTest).GetMethod("Method").GetCustomAttribute<MyAttribute>();

            Console.WriteLine(classIfno.Msg + "  " + fieldIfno.Msg + "  " + methodIfno.Msg);

            Console.ReadLine();
        }
复制代码
复制代码

运行结果: