using System; using System.Reflection; namespace MethodAttribs { publicclass TransactionableAttribute : Attribute { public TransactionableAttribute() { } } class SomeClass { [Transactionable] publicvoid Foo() {} publicvoid Bar() {} [Transactionable] publicvoid Goo() {} } class Test { [STAThread] staticvoid Main(string[] args) { Type type = Type.GetType("MethodAttribs.SomeClass"); foreach(MethodInfo method in type.GetMethods()) { foreach(Attribute attr in method.GetCustomAttributes(true)) { if(attr is TransactionableAttribute) { Console.WriteLine(("{0} is transactionable."),method.Name); } } } } } }
与前一节的例子不同,如果一个类在一个名称空间中(即使是当前名称空间),就必须完全限定它:
Type type = Type.GetType(“MethodAttribs.SomeClass“);
然后使用Tyep.GetMethods方法来获取MethodInfo对象的数组。再用foreach遍历。
有了MethodInfo对象,就可以使用MethodInfo.GetCustomAttributes方法来获取这个方法的所有用户定义属性。
接下来的语句如前一个例子,不再多说了。