字符串和值类型在堆栈上的分配内存
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public static string getMemory(object o) // 获取引用类型的内存地址方法 2 { 3 GCHandle h = GCHandle.Alloc(o, GCHandleType.Pinned); 4 IntPtr addr = h.AddrOfPinnedObject(); 5 return "0x" + addr.ToString("X"); 6 }
1、打印出各个字符的内存地址:
2、打印出各个字符的内存地址及字符相加后的内存地址:
字符串变量a和字符串变量d值相同,会指向同一个内存地址。
3、打印出值类型的内存地址:
对值进行每次操作都会从新生成一个内存地址,即使值相同也会从新分配内存地址。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 static void Main(string[] args) 2 { 3 ////1、 4 //string a = "t"; 5 //Console.WriteLine(getMemory(a)); 6 7 //a += "e"; 8 //Console.WriteLine(getMemory(a)); 9 10 //a += "s"; 11 //Console.WriteLine(getMemory(a)); 12 13 //a += "t"; 14 //Console.WriteLine(getMemory(a)); 15 16 17 ////2、 18 //string a = "t"; 19 //Console.WriteLine(getMemory(a)); 20 21 //string b = "e"; 22 //Console.WriteLine(getMemory(b)); 23 24 //string c = "s"; 25 //Console.WriteLine(getMemory(c)); 26 27 //string d = "t"; 28 //Console.WriteLine(getMemory(d)); 29 30 //string result = a + b + c + d; 31 32 //Console.WriteLine(getMemory(result)); 33 34 35 36 ////3、 37 //int a = 3; 38 //Console.WriteLine(getMemory(a)); 39 40 //int b = a; 41 //Console.WriteLine(getMemory(b)); 42 43 //b = a + 1; 44 //Console.WriteLine(getMemory(b)); 45 46 47 48 string a = "t"; 49 Console.WriteLine(getMemory(a)); 50 51 string b = "e"; 52 Console.WriteLine(getMemory(b)); 53 54 string c = "s"; 55 Console.WriteLine(getMemory(c)); 56 57 string d = "t"; 58 Console.WriteLine(getMemory(d)); 59 60 string result = string.Format("{0}{1}{2}{3}", a, b, c, d); 61 Console.WriteLine(getMemory(result)); 62 63 64 65 Console.ReadKey(); 66 67 //两个字符串具有相同的值,会指向同一个内存地址 68 //对一个字符串进行replace等操作,会从新在内存中生成一个内存地址 69 70 //值类型 对值进行每次操作都会从新生成一个内存地址 71 72 }
结论:
(1)、两个字符串具有相同的值,会指向同一个内存地址;
(2)、对一个字符串进行replace等操作,会从新在内存中生成一个内存地址;
(3)、值类型 对值类型每次操作都会从新生成一个内存地址。