Home > Backend Development > C++ > How Can I Invoke Private Methods Using Reflection in C#?

How Can I Invoke Private Methods Using Reflection in C#?

Linda Hamilton
Release: 2025-01-25 05:21:09
Original
507 people have browsed it

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>
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template