【发布时间】:2018-08-15 11:41:15
【问题描述】:
基本上,为什么会这样?
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.
【问题讨论】:
-
Marshal.SizeOf(a)在这两种情况下都是 4。 -
不会使用
barray.Length作为您的计数更明智吗? -
他在做 Marshal.SizeOf(a),a 是一个 int。
-
@jdweng 肯定有区别,第二个不起作用,也不应该,因为
3 < 4 -
它不起作用,因为您试图从 3 个字节长的数组中提取 4 个字节。没有比这更有趣的了。使用
Marshal.SizeOf很少合适,除非您实际上将数据编组到非托管代码。如果您在手动二进制序列化方案中使用它,请不要。BinaryFormatter和protobuf是您正在尝试重新发明的现有轮子。
标签: c# arrays memorystream