Home >Backend Development >C++ >How Can I Call a C# Function Using Its Name Stored as a String?
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
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!