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(); }
运行结果:
分类:
C# 知识
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源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分库分表方案?