C# で文字列から関数を呼び出す 質問する

C# で文字列から関数を呼び出す 質問する

PHP では次のような呼び出しができることを知っている:

$function_name = 'hello';
$function_name();

function hello() { echo 'hello'; }

これは.Netで可能ですか?

ベストアンサー1

はい。リフレクションを使用できます。次のようになります。

Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);

上記のコードでは、呼び出されるメソッドにアクセス修飾子が必要ですpublic。非パブリック メソッドを呼び出す場合は、パラメータを使用する必要がありますBindingFlags。例BindingFlags.NonPublic | BindingFlags.Instance:

Type thisType = this.GetType();
MethodInfo theMethod = thisType
    .GetMethod(TheCommandString, BindingFlags.NonPublic | BindingFlags.Instance);
theMethod.Invoke(this, userParameters);

おすすめ記事