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 }
  • 相关阅读:
    C#中 File,Directory,FileInfo,DirectoryInfo区别与应用
    C#中设置开机自动运行和关机
    C# 线程手册 第三章 使用线程 小心死锁
    C# WinForm判断Win7下是否是管理员身份运行
    C#应用MemoryStream提高File读取速度
    CodeforcesDouble Profiles
    SRM533 D1 L1
    SRM532 D1 L2
    SRM533 D2 L3
    次小生成树 | 割点 | 割边
  • 原文地址:https://www.cnblogs.com/Tan-sir/p/4862319.html
Copyright © 2011-2022 走看看