【发布时间】:2020-08-06 08:44:48
【问题描述】:
在我的静态 main 函数中,我有以下代码:
string str1 = "aaaaaaaaa";
pointerTest();
Console.WriteLine( "str1 is: " + str1 );
声明为unsafe的静态pointerTest-方法包含以下内容:
string str2 = "aaaaaaaaa";
fixed( char* ptr = str2 )
{
for( int i = 0; i < str2.Length / 3; ++i )
ptr[i] = 'z';
}
Console.WriteLine( "str2 is: " + str2 );
请注意str1 和str2 是如何独立声明的,但内容相同。
这个程序的预期输出是:
str2 is: zzzaaaaaa
str1 is: aaaaaaaaa
当我运行程序时,实际输出会显示:
str2 is: zzzaaaaaa
str1 is: zzzaaaaaa
当我将str2 或str1 更改为不具有完全相同的内容时(例如,在str2 的末尾再添加一个“a”),程序会像预期的那样运行。
如果发现这种行为在 .Net Core 3.1 和 Mono 中都存在(不确定确切的版本,我使用了Repl.It)
我的问题是为什么会发生这种行为以及如何解决它。
【问题讨论】:
标签: c# string pointers reference compiler-optimization