C# 错误:"System.IndexOutOfRangeException: 'Index was outside the bounds of the array.' "



代码:

public static int GetInt(byte[] bytes, int offset) => (bytes[offset] | bytes[++offset] << 8 | bytes[++offset] << 16 | bytes[++offset] << 24);

错误:

System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'

我在网上搜索了一下,但没能解决。

您可能超出了输入数组的范围,正如异常所说。在访问索引之前,请检查索引是否在数组边界内,并尝试使用固定索引而不是递增索引:

public static int getByte(byte[] bytes, int index) {
int result = 0;
if(index < bytes.Length)
result += bytes[index];
else
return result;
if((index+1) < bytes.Length)
result = (result << 8) + bytes[index+1];
else
return result;
if((index+2) < bytes.Length)
result = (result << 8) + bytes[index+2];
else
return result;
if((index+3) < bytes.Length)
result = (result << 8) + bytes[index+3];
else
return result;
return result;
}

您正在传递的字节数组没有偏移量+3个元素。

我的最佳猜测是:

++offset

有两种增量样式,但它们并不相同。

++offset在使用前会增加值

offset++在使用后会增加值。

事实上,我的一个朋友也犯了同样的错误,导致他最终将值初始化为-1。而不是将增量固定为正确的类型。

您也在增加一行中的偏移量。因此,每个值都会有所不同。确保这是你真正想要的。

相关内容

最新更新