代碼如下: public object ExecuteSense(string senseMethod){object result = null;Console.WriteLine(this.GetType());System.Reflection.MethodInfo methodInfo = this.GetType().GetMethod(senseMethod);//獲取具體的函數方法if (methodInfo is System.Reflection.MethodInfo && methodInfo.IsPublic)result = methodInfo.Invoke(this, new object[] { });//在此會彈射出 異常 return result;總會顯示“參數個數不匹配” 求解
1 回答

瀟湘沐
TA貢獻1816條經驗 獲得超6個贊
這個問題很明顯啊,你調用methodInfo.Invoke 方法的時候沒有傳遞參數進去,參數不匹配,當然報錯了。在使用反射機制動態調用方法時,你先要知道此方法需要什么參數,參數的類型,參數的個數等等。比方說我有一個方法:publc void TestMethod(int a, int b); 那么你調用的時候就要這樣寫:
int a = ...;
int b = ...;
methodInfo.Invoke(this, new object[] { a, b });
所以你這個ExecuteSense 方法的簽名應該改為:
public object ExecuteSense(string senseMethod, obejct[] args);
參數在外部傳入。
- 1 回答
- 0 關注
- 783 瀏覽
添加回答
舉報
0/150
提交
取消