基本上,这为什么起作用?
System.IO.Stream stream = new MemoryStream();
int a = 4;
byte[] barray = new byte[a];
stream.Write(barray, 0, Marshal.SizeOf(a));
如果不这样做:
System.IO.Stream stream = new MemoryStream();
int a = 3;
byte[] barray = new byte[a];
stream.Write(barray, 0, Marshal.SizeOf(a));
这是我得到的错误:
The offset and length were greater than allowed for the matrix, or the number is greater than the number of elements from the index to the end of the source collection.
答案 0 :(得分:4)
使用Marshel.SizeOf(a)
时,您要询问内存中对象的大小。由于a
是int
,因此大小始终为4。
说byte[] barray = new byte[a];
时说:
创建一个类型为barray
的名为byte
的数组,其长度为a
。因此,在第一个代码块中创建一个长度为4的数组,在第二个代码块中创建一个长度为3的数组。两个数组都只包含零。
然后您说:将(空)数组写入流,从位置0开始,长度为4(Marshel.SizeOf(a)
始终为4,因为a
是int)。
第一个示例数组的长度为4,因此可以正常工作。第二个示例仅包含3个字节,因此长度不正确,您会收到错误消息。
如果您希望将int显式保存为字节流,可以调用BitConverter
:
System.IO.Stream stream = new MemoryStream();
int a = 4;
byte[] barray = System.BitConverter.GetBytes(a);
stream.Write(barray, 0, Marshal.SizeOf(a));
现在,您说:创建一个名为barray
的数组,该数组将填充整数变量a
的二进制表示形式。
然后将填充数组写入流中。