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

sch*_*nyw 1 .net c# memorystream .net-core

我正在编写一些库代码,其中有一个byte[]在内存中保存一些数据。我想将byte[]viaStream对象的某些部分公开给库使用者。例如,我希望暴露的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);
Run Code Online (Sandbox Code Playgroud)

仅供参考,我在 .NET Core 3.1 上。

Que*_*cus 5

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