Home >Backend Development >C++ >How Can I Invoke Private Methods Using Reflection in C#?
Use reflection to call C# private methods
Dynamically calling private methods, especially when the method name changes based on the input value, requires the use of reflection technology. GetMethod()
By default, the method only obtains public methods and ignores private methods. To access private methods, add GetMethod()
to the BindingFlags
function.
requires combining the BindingFlags.NonPublic
and BindingFlags.Instance
flags. This will contain non-public (private) methods within the scope of the current instance.
The modified code is as follows:
<code class="language-csharp">MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType, BindingFlags.NonPublic | BindingFlags.Instance); dynMethod.Invoke(this, new object[] { methodParams });</code>
This code will successfully retrieve the private method "Draw_" and call it with the provided parameters.
For more information about reflection and BindingFlags
, please refer to the following documentation:
The above is the detailed content of How Can I Invoke Private Methods Using Reflection in C#?. For more information, please follow other related articles on the PHP Chinese website!