自定义特性

1.自定义特性

复制代码
 //AttributeTargets 作用于什么位置(类,枚举,方法,属性。。。)
    [AttributeUsage(AttributeTargets.Class)]
    internal sealed class CustonAttribute:Attribute
    {
        public CustonAttribute(string author, string version, string discription)
        {
            Author = author;
            Version = version;
            Discription = discription;
        } 
        public string Author { get; set; }
        public string Version { get; set; }
        public string Discription { get; set; }
    }
复制代码

2.使用

复制代码
   [Custon("张三","V1.1","自定义特性使用")]
    internal class Program
    {
        static void Main(string[] args)
        {
            //反射获取
            Type t = typeof(Program);
            if (t.IsDefined(typeof(CustonAttribute), false))//检查是否定义了对应的特性
            {
                object[] objs= t.GetCustomAttributes(false);
                foreach (var obj in objs)
                {
                    CustonAttribute item = (CustonAttribute)obj;
                    Console.WriteLine($"Author:{item.Author},Version:{item.Version},Discription:{item.Discription}");
                }
            }
               
        }
    }
复制代码

3.查看结果

 

posted @   后跳  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示