c#字节数组索引超出了数组的界限

c#字节数组索引超出了数组的界限,c#,byte,bytearray,indexoutofboundsexception,C#,Byte,Bytearray,Indexoutofboundsexception,我正在读取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 -

我正在读取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;

}
ReadData=新字节[5];
bytewaiting=Serialcomport.BytesToRead;
while(字节等待>0)
{

ReadData[i++]=(byte)Serialcomport.ReadByte();***接收缓冲区包括串行驱动程序的接收缓冲区以及
串行端口
对象本身的内部缓冲区

由于
BytesToRead
属性同时表示
SerialPort
缓冲区和Windows创建的缓冲区,因此它可以返回比ReadBufferSize属性更大的值。

您应该订阅
DataReceived
事件,而不是通过testoread查看
DataReceived
事件。然后,当新数据到达时,系统会自动调用您

如果您不知道如何在上面指向相应MSDN页面的链接上执行此操作,您将找到一个关于如何订阅活动以及在其中应执行的操作的示例。

旁注:请仔细阅读指南以改进您未来的问题。
i++
在该代码中没有任何意义,因为它从未声明或分配任何合理的value。