object o = i; 此語句的結(jié)果是在堆棧上創(chuàng)建對象 o,而該對象在堆上引用 int 類型的值。該值是賦給變量 i 的值類型值的一個副本。下圖說明了兩個變量 i 和 o 之間的差異。
裝箱轉(zhuǎn)換 在堆棧上 在堆上 i 123 int i=123; o (將i裝箱) object o=i; int 123 也可以(但絕不必要)如下例所示顯式執(zhí)行裝箱: int i = 123; object o = (object) i; 示例 此例將整數(shù)變量 i 通過裝箱轉(zhuǎn)換為對象 o。這樣,存儲在變量 i 中的值就從 123 更改為 456。此例顯示對象保留了內(nèi)容的原始副本,即 123。 // boxing.cs // boxing an integer variable using system; class testboxing { public static void main() { int i = 123; object o = i; // implicit boxing i = 456; // change the contents of i console.writeline("the value-type value = {0}", i); console.writeline("the object-type value = {0}", o); } } 輸出 the value-type value = 456 the object-type value = 123