加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读