我对使用基于字节数组的可写 System.IO.MemoryStream 进行基本实验感到困惑,该实验给出了 ArgumentException
- 数组
newBytes
使用文字初始化 - 使用数组初始化内存流
ms
,并将可写标志设置为True
- 内存流在位置 1 处写入一个字节
VB.net
Try
Dim newBytes() As Byte = {0, 128, 255, 128, 0}
Dim ms As New System.IO.MemoryStream(newBytes, True)
ms.Write({CByte(4)}, 1, 1)
Catch ex as Exception
End Try
C#.net
try
byte() newBytes = {0, 128, 255, 128, 0};
System.IO.MemoryStream ms = new System.IO.MemoryStream(newBytes, true);
ms.Write(byte(4), 1, 1);
catch Exception ex
end try
异常是一个 ArgumentException
,其中包含文本“偏移量和长度超出数组范围或计数大于从索引到源集合末尾的元素数量。”
显然内存流有Length: 5
并且在位置1写入一个字节应该是完全可行的,为什么会有异常(exception)?
最佳答案
MemoryStream.Write
方法具有三个参数:
buffer
- 用于写入数据的缓冲区offset
- 缓冲区中从零开始的字节偏移量,从此处开始将字节复制到当前流count
- 要写入的最大字节数
请注意,第二个参数是输入数组中的偏移量,而不是输出数组中的偏移量。 MemoryStream.Position
属性确定输出中的当前偏移量。
关于.net - 为什么这个简单的 MemoryStream.Write() 实验失败了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52654031/