【问题标题】:c# bytes array index was outside the bounds of the array [duplicate]c#字节数组索引超出了数组的范围[重复]
【发布时间】:2016-09-02 05:50:36
【问题描述】:

我正在读取 5 字节数组

ReadData = new byte[5];

bytewaiting = Serialcomport.BytesToRead;

while (bytewaiting > 0)

{

   ReadData[i++] = (byte)Serialcomport.ReadByte(); **<--Error: Index was outside the bounds of the array**

   bytewaiting = bytewaiting - 1;

}

【问题讨论】:

  • 旁注:请仔细阅读minimal reproducible example 指导以改进您未来的问题。 i++ 在该代码中毫无意义,因为它从未声明或分配任何合理的值。

标签: c# byte bytearray indexoutofboundsexception


【解决方案1】:

接收缓冲区包括串行驱动程序的接收缓冲区以及SerialPort对象本身的内部缓冲。

因为BytesToRead 属性代表SerialPort 缓冲区和Windows 创建的缓冲区,它可以返回比ReadBufferSize 属性更大的值。

您应该订阅DataReceived 事件,而不是关注BytesToRead。然后当有新数据到达时会自动调用。

如果您不知道如何在上面指向相应 MSDN 页面的链接上执行此操作,您将找到有关如何订阅事件以及您应该在其中做什么的示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-11
    • 2016-05-12
    • 1970-01-01
    • 2015-11-06
    • 2010-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多