C# 参数计数不匹配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1636629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parameter Count Mismatch
提问by BSchlinker
Having trouble with the following segment of code. I'm getting a parameter count mismatch.
以下代码段有问题。我得到一个参数计数不匹配。
I've had to write this because of problems with multiple threads and unsafe updates.
由于多线程和不安全更新的问题,我不得不写这个。
delegate void data_INPUTDelegate(object sender, System.IO.Ports.SerialDataReceivedEventArgs e);
private void data_INPUT(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string data = serialPort.ReadLine();
string[] tokens = data.Split(':');
if (tokens[0] == "$SENSOR")
{
if (label_sensorValue.InvokeRequired)
{
data_INPUTDelegate del = new data_INPUTDelegate(data_INPUT);
label_sensorValue.Invoke(del,new object[] {tokens[1]});
}
else
{
label_sensorValue.Text = tokens[1];
}
}
}
采纳答案by ybo
I guess the error comes from this line:
我想错误来自这一行:
label_sensorValue.Invoke(del,new object[] {tokens[1]});
You pass only one parameter to del (tokens[1]
) but it has two parameters (sender and e)
您只向 del ( tokens[1]
)传递一个参数,但它有两个参数(sender 和 e)
EDIT: after carefully reading your code, I suggest that you create a SetSensorValue
method to set the value of label_sensorValue
. Right now you're trying to invoke the event handler with wrong parameters.
编辑:仔细阅读您的代码后,我建议您创建一个SetSensorValue
方法来设置label_sensorValue
. 现在您正在尝试使用错误的参数调用事件处理程序。
private void data_INPUT(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string data = serialPort.ReadLine();
string[] tokens = data.Split(':');
if (tokens[0] == "$SENSOR")
{
SetSensorValue(tokens[1]);
}
}
delegate void SetSensorValueDelegate(string value);
private void SetSensorValue(string value)
{
if (label_sensorValue.InvokeRequired)
{
SetSensorValueDelegate del = new SetSensorValueDelegate(SetSensorValue);
label_sensorValue.Invoke(del, new object[] {value});
}
else
{
label_sensorValue.Text = value;
}
}
回答by SLaks
Your problem is that you're calling a two-parameter delegate with only one parameter.
您的问题是您正在调用一个只有一个参数的双参数委托。
The following line
以下行
label_sensorValue.Invoke(del,new object[] {tokens[1]});
invokes the delegate on the UI thread with the parameter tokens[1]
.
使用参数调用 UI 线程上的委托tokens[1]
。
Since the delegate requires two parameters, it's failing. In addition, the delegate expects an object
and a SerialDataReceivedEventArgs
, not a string.
由于委托需要两个参数,所以它失败了。此外,委托需要一个object
和一个SerialDataReceivedEventArgs
,而不是一个字符串。
To fix this, you should invoke an anonymous method instead of the delegate.
要解决此问题,您应该调用匿名方法而不是委托。
For example (in C# 3):
例如(在 C# 3 中):
label_sensorValue.Invoke(new Action(() => label_sensorValue.Text = tokens[1]));