为什么这个简单的 MemoryStream.Write() 实验失败了?

J C*_*ins 2 .net memorystream

System.IO.MemoryStream我对使用基于字节数组的可写性给出 ArgumentException 的基本实验感到困惑

  1. 该数组newBytes用文字初始化
  2. 内存流ms使用数组进行初始化,并将可写标志设置为True
  3. 内存流在位置1写入一个字节

VB网

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

异常是ArgumentException带有文本“偏移量和长度超出数组范围或计数大于从索引到源集合末尾的元素数”。

显然内存流有Length: 5并且在位置1写入一个字节应该是完全可行的,为什么会有例外?

Ste*_*art 5

MemoryStream.Write方法有三个参数:

  • buffer- 从中写入数据的缓冲区
  • offset- 缓冲区中从零开始的字节偏移量,从该偏移量开始将字节复制到当前流
  • count- 写入的最大字节数

请注意,第二个参数是输入数组中的偏移量,而不是输出数组中的偏移量。该MemoryStream.Position属性确定输出中的当前偏移量。