考慮下面的代碼:如果更改像這樣的字符串的內容會導致異常?
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