Attribute类是所有属性类型的基类。
个人理解Attribute类型的主要作用是为某些需要进行特殊注释的类型快速添加备注信息。
例如:
- using System;
- using System.Collections.Generic;
- using System.Reflection;
- /// <summary>
- /// 标示某个方法是否是Ajax
- /// </summary>
- [AttributeUsage(AttributeTargets.Method,Inherited=true,AllowMultiple=true)]//设置该属性能够使用的类型
- public class AjaxAttribute:Attribute
- {
- private Boolean _async;
- public AjaxAttribute(Boolean async)
- {
- this._async=async;
- }
- public Boolean Async
- {
- get
- {
- return this._async;
- }
- set
- {
- this._async=value;
- }
- }
- }
- public class MyClass
- {
- [AjaxAttribute(true)]
- public void Ajax()
- {
- Console.WriteLine("/t因为我被加了AjaxAttribute因此被访问了");
- }
- public static void RunSnippet()
- {
- Assembly ass=Assembly.GetExecutingAssembly();
- Object obj=ass.CreateInstance("MyClass");
- MethodInfo[] methods= obj.GetType().GetMethods();
- foreach(MethodInfo temp in methods)
- {
- if(temp.GetCustomAttributes(typeof(AjaxAttribute),true).Length==1)
- {
- Console.WriteLine("发现方法"+temp.Name+"具有Ajax属性,Async值为"+((AjaxAttribute)(temp.GetCustomAttributes(typeof(AjaxAttribute),true)[0])).Async.ToString());
- Console.WriteLine("尝试调用本方法:");
- temp.Invoke(obj,new Object[]{});
- Console.WriteLine("调用本方法结束。");
- }
- }
- }
- }
执行后输出结果如下:
发现方法Ajax具有Ajax属性,Async值为True
尝试调用本方法:
因为我被加了AjaxAttribute因此被访问了
调用本方法结束。
Press any key to continue...