有关serialport.read(byte [] buffer,Int32,Int32)的错误 [英] error about serialport.read(byte[] buffer, Int32, Int32)

查看:100
本文介绍了有关serialport.read(byte [] buffer,Int32,Int32)的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目回复了有关使用serialPort1.Read的错误:



my project give back an error about using serialPort1.Read:

byte[] buff={0}; 
serialPort1.Read(buff, 10, 10); 





在button_click事件中,当我按下按钮时,返回错误并显示偏移和长度超出界限对于数组或计数大于从索引到源集合末尾的元素数。

是什么意思?



it's in "button_click" event, when i pressed on button, give back an error and display "Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection."
what does it mean?

推荐答案

嗯,你有什么期望?串口缓冲区中至少有10个字节在等待你吗?你正在加载它们的数组是否足够大20个字节?因为这就是你要求的给我10个字节,但是它们在这个单字节缓冲区中,从第11个字节位置开始



试试这个:

Well, what did you expect? Are there at least 10 bytes in the serial port buffer waiting for you? Is the array you are loading them into big enough for 20 bytes? Because that is what you are asking for "Give me 10 bytes, and but them in this one byte buffer, starting from the eleventh byte location"

Try this:
byte[] buff= new byte[20];
serialPort1.Read(buff, 10, 10);

但相反,请不要使用幻数 - 使用常量,或检查串口长度,以确保至少有你需要的字节数。然后使用该大小来分配缓冲区,记住添加输出偏移所需的任何内容。

But instead, please don't use "magic numbers" - use constants, or check the serial port length to ensure there are at least as many bytes as you need first. Then use that size to allocate your buffer, remembering to add on whatever you need for the output offset.


你应该写

serialPort1.Read(buff,0 ,10);
You should write
serialPort1.Read(buff, 0, 10);


这篇关于有关serialport.read(byte [] buffer,Int32,Int32)的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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