考虑下面的代码:如果更改像这样的字符串的内容会导致异常?
using System;
using System.Runtime.InteropServices;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
const string test = "ABCDEF"; // Strings are immutable, right?
char[] chars = new StringToChar{str=test}.chr;
chars[0] = 'X';
// On an x32 release or debug build or on an x64 debug build,
// the following prints "XBCDEF".
// On an x64 release build, it prints "ABXDEF".
// In both cases, we have changed the contents of 'test' without using
// any 'unsafe' code...
Console.WriteLine(test);
}
}
[StructLayout(LayoutKind.Explicit)]
public struct StringToChar
{
[FieldOffset(0)]
public string str;
[FieldOffset(0)]
public char[] chr;
}
}
通过运行该代码,我们可以改变一个字符串的内容没有异常发生的历史。我们不必宣布任何不安全的代码就可以这样做。这段代码显然非常狡猾!
我的问题是这样的:你认为上面的代码应该抛出异常吗?
[EDIT1:请注意,其他人已经尝试这对我来说,有的人得到不同的结果 - 这是不是太suprising鉴于我在做什么的nastyness ...;)]
[ EDIT2:请注意,我使用Visual Studio 2010的Windows 7旗舰版64位]
[EDIT3:所做的测试字符串常量,这只是为了更狡猾]
重复[我已经问过的问题](http://stackoverflow.com/questions/792735/why-does-this-code-work-without-the-unsafe-keyword):-) – 2010-12-23 14:43:47
非常有趣!看起来这是一个众所周知的问题。 – 2010-12-23 14:50:29