Type.GetMethod 总是返回 null

Kri*_*ris 3 c# reflection methodinfo stack-frame

我想从调用方法中获取一个 MethodInfo 对象,以确定该方法是否设置了特殊属性。

具有调用方法 Run() 的 Programm 类

class Program
    {
        private static RestHandler _handler = new RestHandler();
        static void Main(string[] args)
        {
            Run();
        }

        [Rest("GET")]
        static void Run()
        {   
            _handler.Handler(typeof(Program));
        }
    }
Run Code Online (Sandbox Code Playgroud)

我想确定自定义属性的类

public class RestHandler
    {
        public void Handler(Type t)
        {
            StackFrame frame = new StackFrame(1);
            var method = frame.GetMethod();

            MethodInfo methodInfo = t.GetMethod(method.Name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);

            var attributes = methodInfo.GetCustomAttributes<RestAttribute>();
        }
    }
Run Code Online (Sandbox Code Playgroud)

属性类

 public class RestAttribute : Attribute
    {
        public RestAttribute(string method)
        {
            Method = method;
        }

        public string Method { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

我的问题是 MethodInfo 对象 ( methodInfo) 始终为空,即使堆栈帧中的方法对象设置正确。该属性method.Name返回调用方法的正确名称。为什么methodInfo对象总是为空?

Ogu*_*gul 5

这是一个私有方法:

static void Run()
Run Code Online (Sandbox Code Playgroud)

添加 BindingFlags.NonPublic 以通过反射访问它

MethodInfo methodInfo = t.GetMethod(method.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
Run Code Online (Sandbox Code Playgroud)