There are a group of private methods in my class, and I need to call one dynamically based on an input value. Both the invoking code and the target methods are in the same instance. The code looks like this:
MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType);
dynMethod.Invoke(this, new object[] { methodParams });
In this case, GetMethod()
will not return private methods. What BindingFlags
do I need to supply to GetMethod()
so that it can locate private methods?
Simply change your code to use the overloaded version of
GetMethod
that accepts BindingFlags:Here's the BindingFlags enumeration documentation.
And if you really want to get yourself in trouble, make it easier to execute by writing an extension method:
And usage:
Invokes any method despite its protection level on object instance. Enjoy!
Microsoft recently modified the reflection API rendering most of these answers obsolete. The following should work on modern platforms (including Xamarin.Forms and UWP):
Or as an extension method:
Note:
If the desired method is in a superclass of
obj
theT
generic must be explicitly set to the type of the superclass.If the method is asynchronous you can use
await (Task) obj.InvokeMethod(…)
.Read this (supplementary) answer (that is sometimes the answer) to understand where this is going and why some people in this thread complain that "it is still not working"
I wrote exactly same code as one of the answers here. But I still had an issue. I placed break point on
It executed but
mi == null
And it continued behavior like this until I did "re-build" on all projects involved. I was unit testing one assembly while the reflection method was sitting in third assembly. It was totally confusing but I used Immediate Window to discover methods and I found that a private method I tried to unit test had old name (I renamed it). This told me that old assembly or PDB is still out there even if unit test project builds - for some reason project it tests didn't built. "rebuild" worked
BindingFlags.NonPublic
will not return any results by itself. As it turns out, combining it withBindingFlags.Instance
does the trick.