c#通过Span / Memory和MemoryMarshal修改interned字符串
发布时间:2020-12-15 22:53:26 所属栏目:百科 来源:网络整理
导读:我开始深入研究名为Span和Memory的新的C#/ .net核心功能,到目前为止它们看起来非常好. 但是,当我遇到MemoryMarshal.AsMemory方法时,我发现了以下有趣的用例: const string source1 = "immutable string";const string source2 = "immutable string";var mem
我开始深入研究名为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字符串(在Windows 10 x64,.net471和.netcore2.1上测试).并且据我所知,现在可以在一个地方修改任何被拦截的字符串,然后对该字符串的所有引用都将使用更新的值. 有没有办法阻止这种行为?是否可以“unintern”字符串? 解决方法
这就是它的工作方式
MemoryMarshal.AsMemory(ReadOnlyMemory) Method
更多你不应该做的事情 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |