[英]C#, Index was outside the bounds of the array
我有以下代码:
void serialport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string serialData = serialport.ReadExisting().Replace("/n", "");
string[] splitSerialData = serialData.Split(new Char[] {','}); //Split up the data
this.Invoke(new Action(delegate()
{
this.temperatureLabel.Text = splitSerialData[0];
}));
}
它工作正常,但是当我这样做时:
void serialport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string serialData = serialport.ReadExisting().Replace("/n", "");
string[] splitSerialData = serialData.Split(new Char[] {','}); //Split up the data
this.Invoke(new Action(delegate()
{
this.temperatureLabel.Text = splitSerialData[0];
this.lightLevelLabel.Text = splitSerialData[1];
}));
}
它不起作用,并说“索引超出了数组的范围”。
您收到此错误,因为serialData
不包含逗号。 因此,结果数组包含一个元素,表达式splitSerialData[1]
引发IndexOutOfRangeException。
这意味着拆分仅返回一个元素-整个字符串。 索引1处没有数组元素,因此
splitSerialData[1]
抛出IndexOutOfBounds
异常。
反过来,这意味着您传递的字符串不包含逗号','
字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.