【发布时间】:2019-06-01 15:11:40
【问题描述】:
我从 C# 中的 System.Buffers.MemoryPool<T> 和 System.Memory<T> 开始,希望减少字节数组的分配。
我有一堆字节和字节数组,我需要将它们复制到单个字节数组(用于仅适用于byte[],而不适用于Span/Memory 的方法)。我正在做这样的事情:
byte aByte = 0x01;
byte[] aByteArray = { 0x02, 0x03, 0x04 };
byte[] anotherByteArray = { 0x05, 0x06, 0x07 };
using (var buffer = MemoryPool<byte>.Shared.Rent(7))
{
Span<byte> target;
target = buffer.Memory.Slice(0, aByteArray.Length).Span;
aByteArray.CopyTo(target);
target = buffer.Memory.Slice(aByteArray.Length, anotherByteArray.Length).Span;
aByteArray.CopyTo(target);
// How to copy a single byte?
}
所以,我想出了如何将字节数组复制到缓冲区,但不知道如何设置单个字节。我试过buffer.Memory.Span[0] = aByte,但Span 没有setter。
【问题讨论】:
-
buffer.Memory.Span[0] = aByte;为我工作。 -
有趣的是,我只检查了索引器的文档:docs.microsoft.com/en-us/dotnet/api/…。它说索引器可以用于获取和设置,但是索引器的声明表明它只有一个getter。也许较新版本的 .NET Core 具有 setter,而较旧版本则没有。我不知道...
-
检查你不会以某种方式结束 IReadOnlyMemory/IReadOnlySpan
-
Getter 是 ref 返回,所以不需要 setter,也不能为 ref 返回属性定义 setter。此外,我在 .NET Framework 或 .NET Core 中使用它也没有任何问题。如果您在尝试使用它时遇到任何编译错误,那么您应该将其添加到问题中。
-
@PetSerAl gah,你是对的 - 编译时没有错误,只是在 Visual Studio 中显示... ReSharper 让我再次知道!