Home >Backend Development >C++ >How Can I Call a C# Function Using Its Name Stored as a String?

How Can I Call a C# Function Using Its Name Stored as a String?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-26 02:11:08297browse

How Can I Call a C# Function Using Its Name Stored as a String?

The name call function stored in the string is called

Many programming languages ​​(including PHP) are allowed to quote the dynamic calling function through string. C# provides a rich reflex function, so this function can also be implemented in the .NET framework.

Use reflection to perform dynamic functions

To call a function identified by a string in C#, you can use reflection. The following code fragment demonstrates how to achieve:

In this code, the name of the method to call is stored in variable

. By obtaining the instance (
<code class="language-csharp">Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);</code>
) of the current object, the

method is used to obtain the reference to the method according to the name. Finally, the method is used to execute the method to pass the target object (this) and any necessary parameter. TheCommandString Type Visit private methods thisType GetMethod Invoke It should be noted that the method to call must be accessible in the context of the reflection operation. By default, the method of using private access to modifiers cannot be accessed in this method. To solve this problem, you can include

parameters in the call, as shown below:

Through this modification, the

and

binding flags are specified, allowing the call method, regardless of its access to the modifier. GetMethod

The above is the detailed content of How Can I Call a C# Function Using Its Name Stored as a String?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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