使用参数调用方法会出错
本文关键字:出错 方法 调用 参数 | 更新日期: 2023-09-27 18:36:08
尝试调用行val = (bool)method.Invoke(instance, args);
上另一个类中的方法时,我收到错误Parameter count mismatch.
该方法只有一个参数,并且(我认为)我将单个参数作为对象传递,因此不确定为什么会出现错误。
请有人建议我的代码有什么问题吗?
class firstClass
{
public bool MethodXYZ(System.Windows.Forms.WebBrowser Wb,
string debug_selectedOption)
{
object[] args = new object[] { Wb, debug_selectedOption };
string methodToInvoke = System.Reflection.MethodBase.GetCurrentMethod().Name;
return runGenericMethod(methodToInvoke, args);
}
private bool runGenericMethod(string methodToInvoke, object[] args)
{
bool val = false;
string anotherClass = args[1].ToString();
Type t = Type.GetType("ProjectXYZ." + anotherClass);
MethodInfo method = t.GetMethod(methodToInvoke);
var constructorInfo = t.GetConstructor(new Type[0]);
if (constructorInfo != null)
{
object instance = Activator.CreateInstance(t);
val = (bool)method.Invoke(instance, args);
}
//........
return val;
}
}
class anotherClass
{
public bool MethodXYZ(object[] args)
{
return true;
}
}
Invoke
采用对象数组来支持可变数量的参数。 在您的情况下,您只有一个参数,该参数本身位于对象数组中。 因此,您需要创建一个新对象数组,其唯一成员是原始对象数组:
val = (bool)method.Invoke(instance, new object[] {args});
试试这个
val = (bool)method.Invoke(instance, new object[] { args });
Invoke
方法的第二个参数采用object[]
用于传递参数数量 ex:args[0] 作为第一个参数,args[1] 作为第二个参数,依此类推。
因此,当您传递 object[] 运行时假设您正在传递多个参数,为了向运行时明确表示,您需要包装在另一个只有一个元素的 object[] 中,因此它作为第一个参数传递