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

djp*_*djp 6 c#

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

Dat*_*han 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
{
}
Run Code Online (Sandbox Code Playgroud)