Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Unboxing trong C#

Boxing: Value type -> Reference type (object) - implicit.

Unboxing: Reference type -> Value type - explicit cast.

int x = 30;
object obj = x;        // Boxing (implicit)
int unboxed = (int)obj; // Unboxing (explicit cast)

Ví dụ với ArrayList

int x = 5;
ArrayList list = new ArrayList();
list.Add(x);           // Boxing
int y = (int)list[0];  // Unboxing

Chi tiết

  • Boxing: Cấp phát object trên heap, copy value vào
  • Unboxing: Kiểm tra type, copy value ra khỏi object
  • Unboxing sai type -> InvalidCastException
  • Performance: Boxing/unboxing tốn chi phí (allocation, copy, GC pressure)

Tránh Boxing

  • Dùng Generic: List<int> thay ArrayList
  • Dùng ref/out parameter
  • Interface constraint: where T : struct
  • ValueTuple thay Tuple class

Lưu ý: Unboxing chỉ hoạt động nếu object được boxed từ CHÍNH type đó. (long)(object)5 -> InvalidCastException (boxed int, unbox long).