Bin*_*Sam 10 c# string immutability
在我上次的c#访谈中,
我被要求证明C#字符串的不变性,我知道c#字符串的不变性意味着什么,但是有可能通过代码证明c#字符串的不变性吗?请问我有一个示例代码片段吗?提前致谢
我能证明string是不是一成不变的.我需要做的就是显示一些变异的代码string,如下所示:
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);
// The following line is even more disturbing, since the constant
// string "ABCDEF" has been mutated too (because the interned 'constant' string was mutated).
Console.WriteLine("ABCDEF");
}
}
[StructLayout(LayoutKind.Explicit)]
public struct StringToChar
{
[FieldOffset(0)] public string str;
[FieldOffset(0)] public char[] chr;
}
}
Run Code Online (Sandbox Code Playgroud)
现在是否应该将其视为C#中的错误是另一回事.:)(答案可能FieldOffset应该被认为是unsafe- 上面的代码据称是safe,因此不string应该是可变的.)
此外,我认为你可以合理地认为这string在精神上是不可改变的,即使有一些愚蠢的边缘案例违反了它在所谓的安全代码中的不变性.