C# の文字列を介して関数を呼び出す
PHP は、以下に示すように、文字列を介して関数を呼び出すことができます:
<code class="language-php">$function_name = 'hello'; $function_name(); function hello() { echo 'hello'; }</code>
同様の機能を .Net で実装できますか?
答え:
はい、.Net はリフレクションを使用して、文字列を通じて関数を呼び出すことができます。その方法は次のとおりです:
<code class="language-csharp">Type thisType = this.GetType(); MethodInfo theMethod = thisType.GetMethod(TheCommandString); theMethod.Invoke(this, userParameters);</code>
上記のコードでは、呼び出されるメソッドにはパブリック アクセス修飾子が必要です。非パブリック メソッドを呼び出す必要がある場合は、次のように BindingFlags パラメーターを使用できます:
<code class="language-csharp">Type thisType = this.GetType(); MethodInfo theMethod = thisType .GetMethod(TheCommandString, BindingFlags.NonPublic | BindingFlags.Instance); theMethod.Invoke(this, userParameters);</code>
以上がC# ではリフレクションを使用して文字列から関数を呼び出すことができますか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。