自定义Attribute
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct) ] public class AuthorAttribute : System.Attribute { private string name; public double version; public AuthorAttribute(string name) { this.name = name; version = 1.0; } }
添加一个Attribute,从System.Attribute继承
使用的地方,在类的定义上面添加
[Author("P. Ackerman", version = 1.1)] class SampleClass { // P. Ackerman's code goes here... }
以上的代码,可以理解成
Author anonymousAuthorObject = new Author("P. Ackerman"); anonymousAuthorObject.version = 1.1;
但是注意这个代码的执行时机,是有人调用了GetCustomAttributes这样的方法,才会导致Attribute构造
如何检查
System.Attribute[] attrs = System.Attribute.GetCustomAttributes(typeof(SampleClass)); // Displaying output. foreach (System.Attribute attr in attrs) { if (attr is Author) { Author a = (Author)attr; System.Console.WriteLine(" {0}, version {1:f}", a.GetName(), a.version); } }
分类:
c# 语言基础
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?