在计时器的刻度上,我从传感器读取9字节的数据,我将读取的字符串转换为十六进制,数据为01-03-04-0A-D5-15-A9-26-FD 现在与我有关的唯一数据是第4和第5个元素,我正在使用split命令拆分字符串,但是当我尝试通过索引3访问第4个元素时,仍然无法访问异常弹出Indexoutofrangeexception
private void timer1_Tick(object sender, EventArgs e)
{
// timer1.Enabled = false;
serialPort1.Write(query, 0, query.Length);
incoming = serialPort1.ReadExisting();
ba = Encoding.Default.GetBytes(incoming);
var hexString = BitConverter.ToString(ba);
textBox1.Text = incoming;
textBox2.Text = hexString;
string[] splittedResult = hexString.Split('-');
textBox3.Text = splittedResult[3];
//label1.Text = splittedResult[1];
// textBox3.Text = Convert.ToString(hexString.Length);
timer1.Enabled = true;
}
答案 0 :(得分:2)
也许hexString为null或它的值比您想象的要短。试试这个:
...
string[] splittedResult = hexString.Split('-');
if (splittedResult.Length >=4 ) // check lenght
textBox3.Text = splittedResult[3];
...