Attribute注解

本文探讨了C#中特性(Attribute)的应用,包括如何定义自定义特性、使用系统提供的特性如[Obsolete]来标记不建议使用的类或方法,并演示了如何在运行时通过反射获取这些特性信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1  class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             //Attribute注解,Attribute是附加到方法、属性、类等上面的特殊的标签,在类Type信息初始化的加载
 6             //无法再运行时修改
 7             Type type = typeof(Person);
 8             object[] attrs =
 9                 type.GetMethod("Hello").GetCustomAttributes(typeof(RuPengAttribute), false);
10             for (int i = 0; i < attrs.Length; i++)
11             {
12                 RuPengAttribute ra = (RuPengAttribute)attrs[i];
13                 Console.WriteLine(ra.Name);
14             }
15 
16             /*
17             Person p1 = new Person();
18             p1.F1();*/
19            // type = typeof(SqlConnection);
20             var methods = type.GetMethods();
21             foreach (var method in methods)
22             {
23                 object[] obAttrs = method.GetCustomAttributes(typeof(ObsoleteAttribute), false);
24                 if (obAttrs.Length > 0)
25                 {
26                     ObsoleteAttribute oa = (ObsoleteAttribute)obAttrs[0];
27                     Console.WriteLine("注意,"+method.Name+"不再推荐使用,因为:"+oa.Message);
28                 }
29             }
30             Console.ReadKey();
31         }
32     }
33 
34     [Obsolete("这个类不能用,否则后果自负")]
35     class Person
36     {
37         //在Hello方法的描述信息MethodInfo上粘了一个RuPengAttribute对象
38         //注解的值必须是常量,不能是动态算出来
39         //[RuPengAttribute(Name=DateTime.Now.ToString())]
40         //一般特性的类型都以Attribute结尾,这样用的时候就不用写“Attribute”
41         //Attribute:注解、注释、特性、属性。。。
42         [RuPeng(Name = "rupeng")]
43         public void Hello()
44         {
45         }
46         [Obsolete("这个方法有bug,我不想修复了,调用Hello可以达到同样的效果,而且没有没有bug")]
47         public void F1()
48         {
49 
50         }
51     }
 1 namespace ConsoleApplication2
 2 {
 3     [AttributeUsage(AttributeTargets.Method)]
 4     class RuPengAttribute:Attribute
 5     {
 6         public RuPengAttribute()
 7         {
 8         }
 9 
10         public RuPengAttribute(string name)
11         {
12             this.Name = name;
13         }
14 
15         public string Name { get; set; }
16     }
17 }

 

转载于:https://www.cnblogs.com/Tan-sir/p/4862319.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值