字符串不变性

Aar*_*els 12 .net string immutability

字符串不变性是通过语句还是通过语句中的字符串来工作的?

例如,我了解以下代码将在堆上分配两个字符串.

string s = "hello ";
s += "world!";
Run Code Online (Sandbox Code Playgroud)

"你好"将留在堆上,直到垃圾收集; 现在引用"你好世界!" 在堆上.但是,以下行在堆上分配了多少个字符串... 1或2?此外,是否有工具/方法来验证结果?

string s = "goodbye " + "cruel world!";
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 21

编译器对字符串连接有特殊处理,这就是为什么第二个例子只有一个字符串.而"实习"意味着即使你运行这条线20000次,仍然只有1个字符串.

重新测试结果......最简单的方法(在这种情况下)可能是看反射器:

.method private hidebysig static void Main() cil managed
{
    .entrypoint
    .maxstack 1
    .locals init (
        [0] string s)
    L_0000: ldstr "goodbye cruel world!"
    L_0005: stloc.0 
    L_0006: ldloc.0 
    L_0007: call void [mscorlib]System.Console::WriteLine(string)
    L_000c: ret 
}
Run Code Online (Sandbox Code Playgroud)

正如您所见(ldstr),编译器已经为您完成了此操作.