Attribute注解
2015-10-08 21:14
295 查看
class Program { static void Main(string[] args) { //Attribute注解,Attribute是附加到方法、属性、类等上面的特殊的标签,在类Type信息初始化的加载 //无法再运行时修改 Type type = typeof(Person); object[] attrs = type.GetMethod("Hello").GetCustomAttributes(typeof(RuPengAttribute), false); for (int i = 0; i < attrs.Length; i++) { RuPengAttribute ra = (RuPengAttribute)attrs[i]; Console.WriteLine(ra.Name); } /* Person p1 = new Person(); p1.F1();*/ // type = typeof(SqlConnection); var methods = type.GetMethods(); foreach (var method in methods) { object[] obAttrs = method.GetCustomAttributes(typeof(ObsoleteAttribute), false); if (obAttrs.Length > 0) { ObsoleteAttribute oa = (ObsoleteAttribute)obAttrs[0]; Console.WriteLine("注意,"+method.Name+"不再推荐使用,因为:"+oa.Message); } } Console.ReadKey(); } } [Obsolete("这个类不能用,否则后果自负")] class Person { //在Hello方法的描述信息MethodInfo上粘了一个RuPengAttribute对象 //注解的值必须是常量,不能是动态算出来 //[RuPengAttribute(Name=DateTime.Now.ToString())] //一般特性的类型都以Attribute结尾,这样用的时候就不用写“Attribute” //Attribute:注解、注释、特性、属性。。。 [RuPeng(Name = "rupeng")] public void Hello() { } [Obsolete("这个方法有bug,我不想修复了,调用Hello可以达到同样的效果,而且没有没有bug")] public void F1() { } }
namespace ConsoleApplication2 { [AttributeUsage(AttributeTargets.Method)] class RuPengAttribute:Attribute { public RuPengAttribute() { } public RuPengAttribute(string name) { this.Name = name; } public string Name { get; set; } } }
相关文章推荐
- C语言基础知识
- ocp-211
- 【ShancoLove】带你看数据结构——第三课:线性表链式结构(单链表)
- C++ Primer const变量
- 在两个activity之间传送数据
- 万能药水(贪心)
- React Native入门遇到的一些问题
- 智能车学习(五)—— dac学习
- RHCE7 管理II-5管理进程的优先级
- 常用的开源游戏服务器框架
- ocp-210
- 剑指offer—把字符串转换成整数
- 匿名内部类和内部类
- 【读书笔记】GCD-网络编程要不要使用GCD
- XSS跨站脚本攻击剖析与防御
- 【读书笔记】GCD-网络编程要不要使用GCD
- Codeforces Round #324 (Div. 2)C. Marina and Vasya set
- Anroid常用的辅助类(一)——网络相关
- hdoj Work 5326 (并查集+技巧) 好题
- 如何将GDB中需要的调试信息输出到文件