Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type.GetMethod returns always null

I want to get a MethodInfo object from the calling method to determine if there is a special attribute set on that method.

The Programm class with the calling method Run()

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

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

The Class where I would like to determine the custom attribute

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>();
        }
    }

The attribute class

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

        public string Method { get; set; }
    }

My problem here is that the MethodInfo object (methodInfo) is always null even the method object from the stack frame ist set correctly. The property method.Name returns the correct name of the calling method. Why the methodInfo object is always null?

like image 387
Kris Avatar asked Jul 24 '26 13:07

Kris


1 Answers

This is a private method:

static void Run()

Add BindingFlags.NonPublic to access it via reflection

MethodInfo methodInfo = t.GetMethod(method.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
like image 71
Oguz Ozgul Avatar answered Jul 27 '26 04:07

Oguz Ozgul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!