问题:索引超出了数组的范围。 [英] Problem : Index was outside the bounds of the array.

查看:465
本文介绍了问题:索引超出了数组的范围。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好我尝试创建Ariplan Attitude。在这里我从陀螺仪读取序列但是当我想读取缓冲区的第4或第5个元素时,我得到了这个错误(索引超出了C#中数组的范围)

it看起来当我放入字节时它无法读取第4和第5个元素。

如何才能访问此元素



第四个元素缓冲区[4对于正数或负数,读取0或1,第五个元素缓冲区[5]显示旋转的主要数字。



我的问题是如何阅读 buffer [4] & buffer [5] 来自串口,如下所示(十六进制): 68 07 00 81(00)(00)98 20



Mycode:

Hi guys i try to create Ariplan Attitude . in here i read the serial from gyro but when i wanna read the 4th or 5th element of buffer i cant, i get this error ("Index was outside the bounds of the array in C#")
it seem when i put bytes it cant read 4th and 5th element.
how can i access to this element

the fourth element buffer[4] is read 0 or 1 for positive or negative , the fifth element buffer[5] is show the main number for rotation.

My Question is how can i read the buffer[4] & buffer[5] from serial like this (in Hex): 68 07 00 81 (00) (00) 98 20?

Mycode:

private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {

            // Obtain the number of bytes waiting in the port's buffer
            int bytes = serialPort1.BytesToRead;

            // Create a byte array buffer to hold the incoming data

            byte[] buffer = new byte[bytes];
            

            // Read the data from the port and store it in our buffer
           // if (buffer.Length == 7 )
             serialPort1.Read(buffer, 0, bytes); //bytes
           
             
            

            Log(LogMsgType.Incoming, ByteArrayToHexString(buffer));
           
         //   RxString = port.ReadLine();
         //   ArduinoData = RxString.Split(',', '\n', '\r');
          //  if (ArduinoData.Count() == 7) //ensures we have all data, plus line end ("\n" or "\r")
            if (buffer.Count() == bytes)
            {

                if (buffer[4] == 0) // <--- Problem

                    PitchAngle = Convert.ToDouble(buffer[5]);//<--- Problem
                else
                    PitchAngle = -1.0 * Convert.ToDouble(buffer[5]);//<--- Problem
                // RollAngle = -1.0 * Convert.ToDouble(buffer[5]) * Math.PI / 180;//<--- Problem
                // YawAngle = -1.0 * Convert.ToDouble(ArduinoData[6]) * Math.PI / 180;
                // if (YawAngle < -Math.PI) YawAngle = YawAngle + Math.PI;
                Invalidate();
            }
    
        }

推荐答案

如果要访问数组的第五项(即 buffer [4] )然后第一以确保这样的项目存在,即数组长度至少 5

既然你事先不知道你需要从串口获得多少字节缓冲,即将多事件处理程序调用中收集的数据累积到缓冲区中,并且只有在累积的数据具有所需的最小大小之后才处理这样的缓冲区。
If you want to access the fifth item of an array (namely buffer[4]) then you have first to make sure that such an item exists, that is array length is at least 5.
Since you don''t know in advance how many bytes you are going to get from the serial port you need buffering, i.e. accumulate data collected in multiple event handler call into a buffer and process such buffer only after the accumulated data has the minimum required size.


代码是这样的不好,我建议扔掉它。问题在于:您总是将计数与''==''运算符进行比较。通过这种方式,很容易犯错误,因为比较 if(buffer.Count()== bytes)会让你执行语句 buffer [4] ,如果由于某种原因, buffer.Count()== 4 bytes == 4 。你不需要提问,在调试器下运行它就足够了。



但是这种编码方式无能为力。你永远不应该硬编码你所有的4,5,7,-1.0等等。只是不要。你需要摆脱你的意大利面条代码。



-SA
The code is so bad that I advise to throw it out. Here is the problem: You always compare count with ''=='' operator. This way, it''s easy to make a bug, just because, say, comparison if (buffer.Count() == bytes) would let you execute the statement with buffer[4], if, by some reason, both buffer.Count() == 4 and bytes == 4. You don''t need to ask questions, it would be enough to run it under the debugger.

But this style of coding cannot do anything good. You should never hard-code all your 4, 5, 7, -1.0 and so on. Just don''t. You need to get rid of your spaghetti code.

—SA


这篇关于问题:索引超出了数组的范围。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆