我正在使用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
}
}
理想情况下,只要有可用空间(PacketWriter
中已定义),我想使用PacketSizes
进行写操作。如果没有足够的空间,我想抛出一个异常。好像MemoryStream
会动态分配更多的空间(如果您写满容量),但是我想要固定的容量。我可以做到这一点而无需每次都检查长度吗?到目前为止,我想到的唯一解决方案是重写Write
的所有BinaryWriter
方法并比较长度,但这很烦人。
答案 0 :(得分: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??");
}
}
这是documented的行为:
根据指定的字节数组初始化MemoryStream类的新的不可调整大小的实例。