zoukankan      html  css  js  c++  java
  • Attribute注解

     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 }
  • 相关阅读:
    ubuntu 进入临时客户会话页面 转入用户自己页面
    python hmac 加密
    docker 学习
    python try except 捕捉错误得到错误的时候的值
    python2 python3 m2crypto 安装(rsa 私钥文件加密)
    python3 requests 模块 json参数和data参数区别
    爬虫-鸡哥给大家的福利
    常用模块2
    python入门到放弃之 面向对象vs面向过程
    python放弃之 模块和包
  • 原文地址:https://www.cnblogs.com/Tan-sir/p/4862319.html
Copyright © 2011-2022 走看看