我开始深入研究名为Span和Memory的新的C#/ .net核心功能,到目前为止它们看起来非常好.
但是,当我遇到MemoryMarshal.AsMemory方法时,我发现了以下有趣的用例:
但是,当我遇到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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。