C#中透過字串呼叫函數
PHP 可以透過儲存在字串中的函數名稱來呼叫函數。例如:
<code class="language-php">$function_name = 'hello'; $function_name(); function hello() { echo 'hello'; }</code>
.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中文網其他相關文章!