创建一个 MemoryStream 覆盖字节数组的一部分而不复制内存中的数据

Create a MemoryStream that covers a section of a byte array without copying the data in memory

我正在编写一些库代码,其中有一个 byte[] 在内存中保存一些数据。我想通过 Stream 对象向图书馆消费者公开 byte[] 的某些部分。例如,我希望公开的 Stream 能够访问从位置 50 到 byte[] 末尾的数据。公开的 Stream 将是可读和可查找的,但不可写。

有没有一种简单的方法(希望不需要编写我自己的 Stream 实现)而不在内存中创建数据副本?我尝试使用新的 Memory<T> API,但并没有走得太远,因为 MemoryStream 构造函数无法采用 Memory<T> 参数,而且我似乎无法获得byte[] 来自 Memory<byte> 而不进行复制:

byte[] byteArray = new byte[100];
Memory<byte> memory = byteArray;

// Let's say I want to expose the second half of the byte[] via a Stream
var slicedMemory = memory.Slice(50);

// The only way to construct a MemoryStream from Memory<byte> is to call ToArray and get a byte[]
// But this makes a copy in memory, which I want to avoid
var stream = new MemoryStream(slicedMemory.ToArray(), false);

仅供参考,我使用的是 .NET Core 3.1。

您可以简单地使用 MemoryStream - 它具有构造函数:MemoryStream(byte[] array, int index, int count) 它将在给定数组上创建不可更改的流,从请求的索引开始并具有请求的长度。