Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
字节数组中的C#元素初始化失败,空字节初始化失败_C#_Bytearray_Indexoutofboundsexception - Fatal编程技术网

字节数组中的C#元素初始化失败,空字节初始化失败

字节数组中的C#元素初始化失败,空字节初始化失败,c#,bytearray,indexoutofboundsexception,C#,Bytearray,Indexoutofboundsexception,我是新来的,非常感谢您的帮助 谢谢这很正常,因为您只添加了0到3范围内的项目。 您可以首先检查toBuff[someIndex]是否确实有一个值,因此不为null。BitCOnverter.GetBytes返回一个4个检查的数组: 调用BitConverter.GetBytes()返回长度为4的字节数组,因为intNumBuffer是一个大小为4的int 因此,这意味着toBuff的有效指数是0、1、2和3。因此,使用索引4时会出现错误 现在,我想你在写作时想象过: toBuff = BitCo

我是新来的,非常感谢您的帮助


谢谢

这很正常,因为您只添加了0到3范围内的项目。
您可以首先检查toBuff[someIndex]是否确实有一个值,因此不为null。

BitCOnverter.GetBytes返回一个4个检查的数组:

调用
BitConverter.GetBytes()
返回长度为4的字节数组,因为
intNumBuffer
是一个大小为4的
int

因此,这意味着
toBuff
的有效指数是0、1、2和3。因此,使用索引4时会出现错误

现在,我想你在写作时想象过:

toBuff = BitConverter.GetBytes(intNumBuffer);
toBuff的长度为20。嗯,在这一点上确实如此。但是,当您随后覆盖
toBuff
时,您就拥有了一个新的、不同的数组

可能您需要做的是:

byte[] toBuff = new byte[20];
或许:

byte[] toBuff = new byte[20];
Array.Copy(BitConverter.GetBytes(intNumBuffer), toBuff, sizeof(int)); 

其中任何一个都会将调用
GetBytes()
返回的位复制到
toBuff

您想做什么?谢谢您的回答。我只有一个问题,这是否意味着我的数组大小改变了,该数组的内存从20个改为4个字节,其他16个字节是否恢复到可用内存。不,你创建了一个新数组<代码>toBuff是一个参考。
byte[] toBuff = new byte[20];
byte[] toBuff = new byte[20];
Array.Copy(BitConverter.GetBytes(intNumBuffer), toBuff, sizeof(int)); 
byte[] toBuff = new byte[20];
byte[] intBytes = BitConverter.GetBytes(intNumBuffer);
Array.Copy(intBytes, toBuff, intBytes.Length);