如何通过委托查询方法属性?

时间:2010-01-21 04:14:31

标签: c#

我有一个自定义属性的方法。如果我有一个引用此方法的委托,我可以判断委托引用的方法是否具有该属性?

2 个答案:

答案 0 :(得分:3)

使用委托的GetCustomAttributes属性的Method方法。这是一个示例:

    delegate void Del();

    [STAThread]
    static void Main()
    {
        Del d = new Del(TestMethod);
        var v = d.Method.GetCustomAttributes(typeof(ObsoleteAttribute), false);
        bool hasAttribute = v.Length > 0;
    }

    [Obsolete]
    public static void TestMethod()
    {
    }

如果方法具有属性,var v将包含它;否则它将是一个空数组。

答案 1 :(得分:2)

我不确定这是否是一般情况,但我想是的。请尝试以下方法:

class Program
{
    static void Main(string[] args)
    {
        // display the custom attributes on our method
        Type t = typeof(Program);
        foreach (object obj in t.GetMethod("Method").GetCustomAttributes(false))
        {
            Console.WriteLine(obj.GetType().ToString());
        }

        // display the custom attributes on our delegate
        Action d = new Action(Method);
        foreach (object obj in d.Method.GetCustomAttributes(false))
        {
            Console.WriteLine(obj.GetType().ToString());
        }

    }

    [CustomAttr]
    public static void Method()
    {
    }
}

public class CustomAttrAttribute : Attribute
{
}
相关问题