Home >Backend Development >C++ >Can C# Invoke Functions Dynamically from Strings Using Reflection?
PHP can easily call functions through strings. So, can C# implement this function?
Yes, reflection allows you to dynamically execute methods via strings. Here’s how:
<code class="language-csharp">Type thisType = this.GetType(); MethodInfo theMethod = thisType.GetMethod(TheCommandString); theMethod.Invoke(this, userParameters);</code>
This code works because it retrieves the method's MethodInfo using the string representation of the method name.
If you need to call non-public methods, use BindingFlags:
<code class="language-csharp">MethodInfo theMethod = thisType .GetMethod(TheCommandString, BindingFlags.NonPublic | BindingFlags.Instance); theMethod.Invoke(this, userParameters);</code>
This specifies that the method is non-public and instance-specific.
The above is the detailed content of Can C# Invoke Functions Dynamically from Strings Using Reflection?. For more information, please follow other related articles on the PHP Chinese website!