int、struct、enum。儲存於堆疊,不可為 null,傳值語意。class、interface、delegate、array。變數存參考,物件在堆積,可為 null。System.Object (單根繼承)。double val = 77.77;
object boxed = val; // 隱性裝箱
IL 指令:box [mscorlib]System.Double
執行期動作:
boxed)。double unboxed = (double)boxed; // 必須顯式轉型
IL 指令:unbox [mscorlib]System.Double + ldind.r8 (載入值)。
執行期動作:
System.Double (否則擲回 InvalidCastException)。ArrayList.Add(i)) 產生大量短命物件,觸發 Gen 0 GC。List<T> 避免裝箱。where T : struct。ref/out 傳遞值型別避免複製。ArrayList list = new ArrayList();
for (int i = 0; i < 10000; i++) list.Add(i); // 10000 次裝箱!
// 正確做法
List list = new List();
for (int i = 0; i < 10000; i++) list.Add(i); // 零裝箱
另一陷阱:呼叫值型別的 GetHashCode/Equals/ToString 會隱性裝箱,覆寫這些方法可減少裝箱。