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

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