運行下面的測試代碼,可能更加直觀的理解他,下面展現了如何自己定義屬性類並使用.
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication11
...{
class Program
...{
static void Main(string[] args)
...{
//獲取類上的屬性類
foreach (object obj in typeof(TestClass).GetCustomAttributes(false))
...{
Console.WriteLine(obj.GetType().Name + ":" + obj.ToString());
}
//獲取字段屬性類
foreach (object obj in typeof(TestClass).GetFIEld("_aa").GetCustomAttributes(typeof(Test1), true))
...{
Console.WriteLine(obj.GetType().Name + ":" + obj.ToString());
}
//獲取屬性屬性類
foreach (object obj in typeof(TestClass).GetProperty("aa").GetCustomAttributes(typeof(Test1), true))
...{
Console.WriteLine(obj.GetType().Name + ":" + obj.ToString());
}
//獲取方法屬性類
foreach (object obj in typeof(TestClass).GetMethod("test").GetCustomAttributes(typeof(Test1), true))
...{
Console.WriteLine(obj.GetType().Name + ":" + obj.ToString());
}
//獲取字事件性類
foreach (object obj in typeof(TestClass).GetEvent("onTest").GetCustomAttributes(typeof(Test1), true))
...{
Console.WriteLine(obj.GetType().Name + ":" + obj.ToString());
}
Console.Read();
}
}
//測試屬性類,傳入string
public class Test1 : System.Attribute
...{
string strName = "";
public Test1() ...{ }
public Test1(string str)
...{
strName = str;
}
public override string ToString()
...{
return strName;
}
}
//測試屬性類,傳入int
public class Test2 : Attribute
...{
int _f;
public Test2(int f) ...{ _f = f; }
public override string ToString()
...{
return _f.ToString();
}
}
//給class測試
[Test1("jinjazz for TestClass")]
[Test2(12356)]
public class TestClass
...{
//給字段和屬性測試
[Test1("jinjazz for _aa字段 ")]
public string _aa = "";
[Test1("jinjazz for aa 屬性")]
public string aa
...{
get ...{ return _aa; }
}
//給方法和事件測試
[Test1("jinjazz for test 方法")]
public void test() ...{ }
[Test1("jinjazz for onTest 事件")]
public event System.EventHandler onTest;
}
}