我可以为MemoryStream设置固定长度吗?

Ci3*_*Ci3 2 .net c#

我正在BinaryWriter使用一个MemoryStream.

public class PacketWriter : BinaryWriter
{
    public PacketWriter(Opcode op) : base(CreateStream(op))
    {
        this.Write((ushort)op);
    }

    private static MemoryStream CreateStream(Opcode op) {
        return new MemoryStream(PacketSizes.Get(op));
    }

    public WriteCustomThing() {
        // Validate that MemoryStream has space?
        // Do all the stuff
    }
}
Run Code Online (Sandbox Code Playgroud)

理想情况下,PacketWriter只要有可用空间(已经定义PacketSizes),我想使用write .如果没有可用空间,我想要抛出异常.MemoryStream如果你写过容量,似乎只是动态分配更多的空间,但我想要一个固定的容量.我是否可以在不需要每次检查长度的情况下实现此目的?到目前为止,我想到的唯一解决方案是覆盖所有Write方法BinaryWriter并比较长度,但这很烦人.

Jon*_*eet 5

只需提供所需大小的缓冲区即可写入:

using System;
using System.IO;

class Test
{
    static void Main()
    {
        var buffer = new byte[3];
        var stream = new MemoryStream(buffer);
        stream.WriteByte(1);
        stream.WriteByte(2);
        stream.WriteByte(3);
        Console.WriteLine("Three successful writes");
        stream.WriteByte(4); // This throws
        Console.WriteLine("Four successful writes??");
    }
}
Run Code Online (Sandbox Code Playgroud)

这是记录在案的行为:

基于指定的字节数组初始化MemoryStream类的新的不可调整大小的实例.