代码之家  ›  专栏  ›  技术社区  ›  J Collins

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

  •  1
  • J Collins  · 技术社区  · 6 年前

    我被一个使用可写程序的基本实验弄糊涂了 System.IO.MemoryStream

    1. 阵列 newBytes 是用文字初始化的
    2. ms True
    3. 在位置1处用一个字节写入内存流

    图书管理系统

    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 with text“偏移量和长度超出数组的界限或计数大于从索引到源集合结尾的元素数。”

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

    1 回复  |  直到 6 年前
        1
  •  2
  •   Steven Doggart    6 年前

    这个 MemoryStream.Write 方法有三个参数:

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

    MemoryStream.Position 属性确定输出中的当前偏移量。