PHP可以很方便地透過字串呼叫函數。那麼,C#可以實現這個功能嗎?
是的,反射允許您動態地透過字串執行方法。方法如下:
<code class="language-csharp">Type thisType = this.GetType(); MethodInfo theMethod = thisType.GetMethod(TheCommandString); theMethod.Invoke(this, userParameters);</code>
這段程式碼之所以有效,是因為它使用方法名稱的字串表示形式檢索方法的MethodInfo。
如果您需要呼叫非公共方法,請使用BindingFlags:
<code class="language-csharp">MethodInfo theMethod = thisType .GetMethod(TheCommandString, BindingFlags.NonPublic | BindingFlags.Instance); theMethod.Invoke(this, userParameters);</code>
這指定了該方法是非公共的且特定於實例的。
以上是C#可以使用反射從字符串動態調用功能嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!