值類型和引用類型去查看內存地址的方法不一樣。
值類型:1.先設置編譯器可以運行不安全代碼
然后像C++一樣運用指針去打印:
二:引用類型
1.先引入System.Runtime.InteropServices命名空間
2.代碼如下:
usingSystem;
//?獲取地址需要引入的庫
usingSystem.Runtime.InteropServices;
classMainClass
{
? ? ? ? publicstaticstringgetMemory(objecto)//?獲取引用類型的內存地址方法
? ? ? ?{
? ? ? ? ? GCHandle?h?=?GCHandle.Alloc(o,?GCHandleType.Pinned);
? ? ? ? ? IntPtr?addr?=?h.AddrOfPinnedObject();
? ? ? ? ? return"0x"+?addr.ToString("X");
? ? ? }
? ? publicstaticvoidMain?(string[]?args)
? ? {
? ? ? ? int[]?a?=newint[1];
? ? ? ? int[]?b?=newint[1];
? ? ? ? //?b=0?,未賦值前b的地址是:0x8008E8
? ? ? ? Console.WriteLine("b={0,-2},未賦值前b的地址是:{1}",??b[0],getMemory(b));
? ? ? ? a[0]?=?3;
? ? ? ? b?=?a;//?此句賦值是b引用a的地址,此時a和b表示同一個內存空間地址
? ? ? ? b[0]?=?33;
? ? ? ? //?b=33,賦值后b的地址是:0x8008D0
? ? ? ?Console.WriteLine("b={0},賦值后b的地址是:{1}",??b[0],getMemory(b));
? ? ? ?//?a=33,a的地址是:0x8008D0
? ? ? Console.WriteLine("a={0},a的地址是:{1}",??a[0],getMemory(a));
? ?}
}