C# Attribute的用法

 1  using System;
 2  using System.Collections.Generic;
 3  using System.Linq;
 4  using System.Text;
 5  using System.Reflection;
 6 
 7  namespace ConsoleApplication1
 8 {
 9      class Program
10     {
11          static  void Main( string[] args)
12         {
13              // Operation op = new Operation();
14              MethodInfo method =  typeof(Operation).GetMethod( " Add ");
15             Attribute[] atts = Attribute.GetCustomAttributes(method);
16              foreach (Attribute att  in atts)
17             {
18                  if (att.GetType() ==  typeof(CommandAttribute))
19                 {
20                     Console.WriteLine(((CommandAttribute)att).Name +  " , " + ((CommandAttribute)att).Label);
21                 }
22             }
23             Console.ReadLine();
24              return;
25 
26              #region 获取所有的方法属性
27 
28             Operation testClass =  new Operation();
29             Type type = testClass.GetType();
30              //  Iterate through all the methods of the class.
31               foreach (MethodInfo mInfo  in type.GetMethods())
32             {
33                  //  Iterate through all the Attributes for each method.
34                   foreach (Attribute attr  in Attribute.GetCustomAttributes(mInfo))
35                 {
36                      //  Check for the AnimalType attribute.
37                       if (attr.GetType() ==  typeof(CommandAttribute))
38                         Console.WriteLine(
39                              " Method {0} has a CommandAttribute {1},{2} . ",
40                             mInfo.Name, ((CommandAttribute)attr).Label, ((CommandAttribute)attr).Name);
41                 }
42             }
43 
44              #endregion
45 
46 
47 
48             Console.ReadLine();
49         }
50     }
51 
52 
53 
54 
55      public  class Operation
56     {
57         [Command( " AddLabel "" AddName ")]
58          public  void Add()
59         {
60             Console.WriteLine( " Add ");
61         }
62 
63         [Command( " DelLabel "" DelName ")]
64          public  void Del()
65         {
66             Console.WriteLine( " Del ");
67         }
68     }
69 
70     [AttributeUsage(AttributeTargets.Method)]
71      public  class CommandAttribute : Attribute
72     {
73          public  string Label {  getset; }
74          public  string Name {  getset; }
75 
76          public CommandAttribute() { }
77 
78          public CommandAttribute( string label,  string name)
79         {
80              this.Label = label;
81              this.Name = name;
82         }
83     }
84 }

转载于:https://www.cnblogs.com/pnljs/p/3610863.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值