gpt4 book ai didi

c# 通过 Span/Memory 和 MemoryMarshal 修改 interned 字符串

转载 作者:行者123 更新时间:2023-11-30 12:38:23 26 4
gpt4 key购买 nike

我开始研究名为 Span 和 Memory 的新 C#/.net 核心功能,到目前为止它们看起来非常好。然而,当我遇到 MemoryMarshal.AsMemory 方法时,我发现了以下有趣的用例:

const string source1 = "immutable string";
const string source2 = "immutable string";

var memory = MemoryMarshal.AsMemory(source1.AsMemory());

ref char first = ref memory.Span[0];
first = 'X';

Console.WriteLine(source1);
Console.WriteLine(source2);

两种情况下的输出都是 Xmmutable string(在 Windows 10 x64、.net471 和 .netcore2.1 上测试)。据我所知,任何驻留的字符串现在都可以在一个地方进行修改,然后对该字符串的所有引用都将使用更新后的值。

有什么办法可以防止这种行为吗?是否可以“unintern”字符串?

最佳答案

这就是它的工作方式

MemoryMarshal.AsMemory(ReadOnlyMemory) Method

Creates a Memory instance from a ReadOnlyMemory.

Returns - Memory<T> A memory block that represetns the same memory as the ReadOnlyMemory .

Remarks

  • This method must be used with extreme caution. ReadOnlyMemory is used to represent immutable data and other memory that is not meant to be written to. Memory instances created by this method should not be written to. The purpose of this method is to allow variables typed as Memory but only used for reading to store a ReadOnlyMemory.

更多你不应该做的事情

private const string source1 = "immutable string1";

private const string source2 = "immutable string2";

public unsafe static void Main()
{
fixed(char* c = source1)
{
*c = 'f';
}
Console.WriteLine(source1);
Console.WriteLine(source2);
Console.ReadKey();
}

输出

fmmutable string1
immutable string2

关于c# 通过 Span/Memory 和 MemoryMarshal 修改 interned 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53167132/

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