static void Main(string[] args)
        {
            string A = "hello" + "world";
            string B = "helloworld";
            A = "hello";
            Console.Write(B);
            Console.ReadLine();
        }A 和 B 的地址 是一样的:
ILDASM的内容:
.method /*06000001*/ private hidebysig static 
        void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       33 (0x21)
  .maxstack  1
  .locals /*11000001*/ init ([0] string A,
           [1] string B)
  IL_0000:  nop
  IL_0001:  ldstr      "helloworld" /* 70000001 */
  IL_0006:  stloc.0
  IL_0007:  ldstr      "helloworld" /* 70000001 */
  IL_000c:  stloc.1
  IL_000d:  ldstr      "hello" /* 70000017 */
  IL_0012:  stloc.0
  IL_0013:  ldloc.1
  IL_0014:  call       void [mscorlib/*23000001*/]System.Console/*01000012*/::Write(string) /* 0A000010 */
  IL_0019:  nop
  IL_001a:  call       string [mscorlib/*23000001*/]System.Console/*01000012*/::ReadLine() /* 0A000011 */
  IL_001f:  pop在把 hello 附给A 的时候 A 是不是另开辟的一个空间?
不然输出的B 为什么不是Hello?

解决方案 »

  1.   

    是的虽然A跟B初时都是"helloworld",但是是不同的引用,他们是没有关系的,所以你文的B的输出跟A扯不上任何关系
      

  2.   

    那是当然,其实.net是这样作的。
    原则:如果内存有那个空间,就指向它,如果没有,创建再指向。
      

  3.   

    .net中的string类型是一种只读的引用类型  
    string s ="ABC"
    s = "12345"
    这里实际上分配了两段内存 一个用来存放ABC 当你改变s的值时 实际上是新分配一段内存 值为12345 然后把s的指向指到了这个新的内存段 以前那段不能找到了 只有等待垃圾回收
      

  4.   

    所以遇到变化频率比较大的字符串的操作 建议使用stringBuilder类来代替string类型
      

  5.   

    TO:在把 hello 附给A 的时候 A 是不是另开辟的一个空间?
    不然输出的B 为什么不是Hello?是的,说对了..执行这句string A = "hello" + "world";时,A的值是"hellowordld",会在内存找,看是否已有一块内存地址存放着"helloworld",如果没找到,则新开辟一块空间,用于存放"helloworld",并且A指向这块进址...执行string B = "helloworld";时,由于在执行上一句时,在内存已有一块地址存放着"helloworld",所以就不会再重新分配空间了,而只是将B指向"helloworld",也就是说此时A和B指向着同一块地址空间,内容是"helloworld"..执行A = "hello";时,由于内存中没有"hello",所以系统会重新分配一块地址空间,存放"hello",然后A指向这块地址...即最终的结果是A指向了"hello",B指向了"helloworld"...