自定义特性

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 @ 2022-08-08 02:02  后跳  阅读(21)  评论(0编辑  收藏  举报