gpt4 book ai didi

c# - 使用参数调用方法会出错

转载 作者:太空宇宙 更新时间:2023-11-03 19:12:41 25 4
gpt4 key购买 nike

我收到一个错误Parameter count mismatch. 当我尝试在 val = (bool)method.Invoke(instance, args); 行调用另一个类中的方法时;

该方法只有一个参数,(我认为)我将一个参数作为对象传递,所以不确定为什么会出现错误。

有人可以告诉我我的代码有什么问题吗?

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});

关于c# - 使用参数调用方法会出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19456178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com