如何在不分配的情况下从ReadOnlyMemory<char>获取字符串?

问题描述 投票:0回答:1

我们可以从

ReadonlyMemory<char>
获取字符串引用而不需要在堆上重新分配吗?

ReadonlyMemory<char> someChars;//I got ReadOnlyMemory<char> from somewhere
string str = someChars.SomeMethodToGetStringWithoutAllocation();//I am looking for this
c# memory-management allocation
1个回答
0
投票

您应该能够使用 MemoryMarshal 类的 TryGetString 方法引用相同的内存(如注释中所述)。

但是,看看实现,似乎只有当内存最初是从字符串实例获取时才有效,否则此方法将失败(内部方法

GetObjectStartLength
将返回 false)。

© www.soinside.com 2019 - 2024. All rights reserved.