什么都不说了, 一切都在代码里:
1 string a1 = "aaa"; // 在堆中分配"aaa"
2 string a2 = "aaa"; // 堆中已有"aaa", 则不再给"aaa"分配新空间,a2指向a1的地址
3 string a3 = new string("aaa".ToCharArray()); // new产生新的对象,分配新的空间
4
5 Console.WriteLine(object.ReferenceEquals(a1, "aaa")); //Ture
6 Console.WriteLine(object.ReferenceEquals(a1, a2)); //True
7 Console.WriteLine(object.ReferenceEquals(a1, a3)); //False
8
9 string b1 = "bbb";
10
11 string c1 = "aaabbb"; // 定义"aaabbb"
12 string c2 = "aaa" + "bbb"; // "aaa"和"bbb"都是常量, 合成为"aaabbb"指向c1
13 string c3 = a1 + "bbb"; // a1是变量, 则给c3分配新的空间
14 string c4 = a1 + b1; // 同上, c4分配新的空间
15 string c5 = a1 + b1; // 同上, c5分配新的空间
16
17 Console.WriteLine(object.ReferenceEquals(c1, c2)); //True
18 Console.WriteLine(object.ReferenceEquals(c1, c3)); //False
19 Console.WriteLine(object.ReferenceEquals(c1, c4)); //False
20 Console.WriteLine(object.ReferenceEquals(c3, c4)); //False
21 Console.WriteLine(object.ReferenceEquals(c5, c4)); //False
2 string a2 = "aaa"; // 堆中已有"aaa", 则不再给"aaa"分配新空间,a2指向a1的地址
3 string a3 = new string("aaa".ToCharArray()); // new产生新的对象,分配新的空间
4
5 Console.WriteLine(object.ReferenceEquals(a1, "aaa")); //Ture
6 Console.WriteLine(object.ReferenceEquals(a1, a2)); //True
7 Console.WriteLine(object.ReferenceEquals(a1, a3)); //False
8
9 string b1 = "bbb";
10
11 string c1 = "aaabbb"; // 定义"aaabbb"
12 string c2 = "aaa" + "bbb"; // "aaa"和"bbb"都是常量, 合成为"aaabbb"指向c1
13 string c3 = a1 + "bbb"; // a1是变量, 则给c3分配新的空间
14 string c4 = a1 + b1; // 同上, c4分配新的空间
15 string c5 = a1 + b1; // 同上, c5分配新的空间
16
17 Console.WriteLine(object.ReferenceEquals(c1, c2)); //True
18 Console.WriteLine(object.ReferenceEquals(c1, c3)); //False
19 Console.WriteLine(object.ReferenceEquals(c1, c4)); //False
20 Console.WriteLine(object.ReferenceEquals(c3, c4)); //False
21 Console.WriteLine(object.ReferenceEquals(c5, c4)); //False