Leveraging Reflection to Call Private Instance Methods in C#
Dynamically invoking a private method from within the same object requires using GetMethod()
with the correct BindingFlags
. The default behavior of GetMethod()
only returns public members.
To access private instance methods, modify your code like this:
<code class="language-csharp">MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType, BindingFlags.NonPublic | BindingFlags.Instance); dynMethod.Invoke(this, new object[] { methodParams });</code>
The BindingFlags
enum controls the method search. BindingFlags.NonPublic
includes private methods, and BindingFlags.Instance
ensures you're targeting an instance method (not a static one).
The above is the detailed content of How Can I Use Reflection to Invoke Private Instance Methods in C#?. For more information, please follow other related articles on the PHP Chinese website!