string为引用类型,但是他的创建是特殊的,
他直接赋值的话,是现在内存中去寻找有没有一样的,当有的情况下则是讲地址赋值过去,当没有一样的则会重新去内存中创建一个
代码如下:
static void Main(string[] args){string s1 = new string("1");string s2 = "1";string s3 = "1";string s4 = new string("1");string s5 = "2";var addr1 = getMemory(s1);var addr2 = getMemory(s2);var addr3 = getMemory(s3);var addr4 = getMemory(s4);var addr5 = getMemory(s5);s3 = "2";var addr6 = getMemory(s3);Console.WriteLine($"地址1:{addr1} 地址2:{addr2} 地址3:{addr3} 地址4:{addr4} 地址5:{addr5} 地址6:{addr6}");}public static string getMemory(object o) // 获取引用类型的内存地址方法 {// GCHandle h = GCHandle.Alloc(o, GCHandleType.WeakTrackResurrection);//IntPtr addr = GCHandle.ToIntPtr(h);GCHandle h = GCHandle.Alloc(o, GCHandleType.Pinned);IntPtr addr = h.AddrOfPinnedObject();return "0x" + addr.ToString("X");}