gpt4 book ai didi

c# - 使用多个参数调用控件时参数计数不匹配

转载 作者:行者123 更新时间:2023-11-30 21:09:41 25 4
gpt4 key购买 nike

我使用线程在机器上执行一些进程。最终,进度会在另一个线程中报告回来。要使用进程状态更新 GUI,我使用这样的委托(delegate):

public delegate void UpdateProgressDelegate(string description, int scriptnumber);
public void UpdateProgress(string description, int scriptnumber) {
if (treeView.InvokeRequired) {
treeView.Invoke(new UpdateProgressDelegate(UpdateProgress), description, scriptnumber);
return;
}
// Update the treeview
}

为了调用这个委托(delegate),我使用:

form.UpdateProgress("Ready", 3);

调用 Invoke 时,我收到 TargetParameterCountException:参数计数不匹配。我想我可以通过将 string 和 int 参数放在一个对象中来解决这个问题,如下所示:

public delegate void UpdateProgressDelegate(object[] updateinfo);
public void UpdateProgress(object[] updateinfo) {
string description = (string) updateinfo[0];
int scriptnumber = (int) updateinfo[1];
if (treeView.InvokeRequired) {
treeView.Invoke(new UpdateProgressDelegate(UpdateProgress), new object[] { description, scriptnumber });
return;
}
// Update the treeview
}

为了调用它,我使用:

form.UpdateProgress(new object[] {"Ready", 3});

但这也行不通。我一直收到相同的 TargetParameterCountException。有什么办法可以解决这个问题吗?提前致谢!

最佳答案

我会说:用简单的方法来做:

treeView.Invoke((MethodInvoker)delegate {
UpdateProgress(description, scriptnumber);
});

或(同样):

treeView.Invoke((MethodInvoker) () => UpdateProgress(description, scriptnumber));

这为您提供了编译器的静态检查,IIRC MethodInvoker 被显式检查,并使用 Invoke() 而不是 DynamicInvoke(),也让它变得更快。


为什么它不起作用;在你的例子中:

public delegate void UpdateProgressDelegate(object[] updateinfo);

你实际上传递了两个参数;要在此处消除歧义并将单个数组传递给 params,您需要对其进行双重包装:

treeView.Invoke(new UpdateProgressDelegate(UpdateProgress),
new object[] { new object[] {description, scriptnumber }});

基本上,外部数组是“所有参数的数组”,它包含一个元素,这是我们不想作为第一个参数传递的数组 (updateinfo)。

关于c# - 使用多个参数调用控件时参数计数不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8924319/

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