现在的位置: 首页 > 综合 > 正文

查询属性 – 方法属性

2013年06月01日 ⁄ 综合 ⁄ 共 1173字 ⁄ 字号 评论关闭
6.3.2 方法属性
using System;
using System.Reflection;

namespace MethodAttribs
{
    
public class TransactionableAttribute : Attribute
    
{
        
public TransactionableAttribute()
        
{
        }

    }

    
    
class SomeClass
    
{
        [Transactionable]
        
public void Foo()
        
{}
        
        
public void Bar()
        
{}
        
        [Transactionable]
        
public void Goo()
        
{}
    }

    
    
class Test
    
{
        [STAThread]
        
static void 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方法来获取这个方法的所有用户定义属性。
接下来的语句如前一个例子,不再多说了。

抱歉!评论已关闭.