C# 中透過字串呼叫函數
PHP 可以透過字串呼叫函數,如下所示:
$function_name = 'hello'; $function_name(); function hello() { echo 'hello'; }
.Net 是否可以實現類似的功能?
答案:
是的,.Net 可以使用反射透過字串呼叫函數。以下是實作方法:
Type thisType = this.GetType(); MethodInfo theMethod = thisType.GetMethod(TheCommandString); theMethod.Invoke(this, userParameters);
在上述程式碼中,呼叫的方法必須具有公共存取修飾符。如果需要呼叫非公共方法,可以使用 BindingFlags 參數,如下所示:
Type thisType = this.GetType(); MethodInfo theMethod = thisType .GetMethod(TheCommandString, BindingFlags.NonPublic | BindingFlags.Instance); theMethod.Invoke(this, userParameters);
以上是C#可以使用反射從字符串調用功能嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!