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

原文网址: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();
        }
复制代码
复制代码
复制代码

运行结果:

 

posted @   MaxBruce  阅读(1611)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2021-11-16 详解MongoDB中的多表关联查询($lookup)
2021-11-16 数据库设计三大范式
2021-11-16 一、表的设计步骤
2021-11-16 C#简单操作MongoDB
2020-11-16 什么是TCP,什么是UDP,它们两者的区别? 三次握手
2020-11-16 Vue面试中,经常会被问到的面试题/Vue知识点整理
2020-11-16 mysql 数据库 分表后 怎么进行分页查询?Mysql分库分表方案?
点击右上角即可分享
微信分享提示