自定义Attribute的使用

 Attribute类是所有属性类型的基类。

个人理解Attribute类型的主要作用是为某些需要进行特殊注释的类型快速添加备注信息。

例如:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. /// <summary>
  5. /// 标示某个方法是否是Ajax
  6. /// </summary>
  7. [AttributeUsage(AttributeTargets.Method,Inherited=true,AllowMultiple=true)]//设置该属性能够使用的类型
  8. public class AjaxAttribute:Attribute
  9. {
  10.     private Boolean _async;
  11.     public AjaxAttribute(Boolean async)
  12.     {
  13.         this._async=async;
  14.     }
  15.     public Boolean Async
  16.     {
  17.         get
  18.         {
  19.             return this._async;
  20.         }
  21.         set
  22.         {
  23.             this._async=value;
  24.         }
  25.     }
  26. }
  27. public class MyClass
  28. {
  29.     [AjaxAttribute(true)]
  30.     public void Ajax()
  31.     {
  32.         Console.WriteLine("/t因为我被加了AjaxAttribute因此被访问了");
  33.     }
  34.     public static void RunSnippet()
  35.     {
  36.         Assembly ass=Assembly.GetExecutingAssembly();
  37.         Object obj=ass.CreateInstance("MyClass");
  38.         MethodInfo[] methods= obj.GetType().GetMethods();
  39.         foreach(MethodInfo temp in methods)
  40.         {
  41.             if(temp.GetCustomAttributes(typeof(AjaxAttribute),true).Length==1)
  42.             {
  43.                 Console.WriteLine("发现方法"+temp.Name+"具有Ajax属性,Async值为"+((AjaxAttribute)(temp.GetCustomAttributes(typeof(AjaxAttribute),true)[0])).Async.ToString());
  44.                 Console.WriteLine("尝试调用本方法:");
  45.                 temp.Invoke(obj,new Object[]{});
  46.                 Console.WriteLine("调用本方法结束。");              
  47.             }
  48.         }
  49.     }
  50. }

执行后输出结果如下:

 

发现方法Ajax具有Ajax属性,Async值为True
尝试调用本方法:
        因为我被加了AjaxAttribute因此被访问了
调用本方法结束。
Press any key to continue...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值