gpt4 book ai didi

c# - MemoryStream可以设置固定长度吗?

转载 作者:行者123 更新时间:2023-12-02 15:04:56 26 4
gpt4 key购买 nike

我正在使用 MemoryStream 扩展 BinaryWriter

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
}
}

理想情况下,只要有可用空间(已在 PacketSizes 中定义),我就希望使用 PacketWriter 进行写入。如果没有可用空间,我希望抛出异常。如果您写入容量过多,MemoryStream 似乎会动态分配更多空间,但我想要固定容量。我可以实现这一目标而不需要每次都检查长度吗?到目前为止我想到的唯一解决方案是覆盖 BinaryWriter 的所有 Write 方法并比较长度,但这很烦人。

最佳答案

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

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行为:

Initializes a new non-resizable instance of the MemoryStream class based on the specified byte array.

关于c# - MemoryStream可以设置固定长度吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51272928/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com