考虑以下代码:
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:请注意,其他人已经为我尝试过,有些人得到了不同的结果 - 考虑到我正在做的事情的讨厌,这并不太令人惊讶......;)]
[EDIT2:请注意,我在 Windows 7 Ultimate 64 位上使用 Visual Studio 2010]
[EDIT3:将测试字符串设为 const,只是为了让它更加狡猾!]