Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

ความแตกต่างระหว่าง Boxing และ Unboxing ในภาษา C#

Boxing และ Unboxing

C# มีการเชื่อมโยงระหว่าง Value Type (struct, int, bool) และ Reference Type (object, class)

  • Boxing: แปลง Value Type → Object Type (implicit conversion)
  • Unboxing: แปลง Object Type → Value Type (explicit conversion ต้อง cast)

ตารางเปรียบเทียบ

ลำดับหัวข้อBoxingUnboxing
1การทำงานทำให้ object type อ้างอิง value typeดึงค่า value จาก boxed object
2หน่วยความจำคัดลอกค่าจาก Stack ไป Heapคัดลอกค่าจาก Heap กลับ Stack
3ประเภทการแปลงImplicit conversion (อัตโนมัติ)Explicit conversion (ต้อง cast เอง)

ตัวอย่างโค้ด (Java/C#)

public class JavaTester {
    public static void main(String[] args) {
        int val = 119;
        // Boxing
        Object o = val;
        // เปลี่ยนค่า val
        val = 120;
        // Unboxing
        int x = (int)o;
        System.out.println("Value of x is " + x);      // 119
        System.out.println("Value type of val is " + val); // 120
        System.out.println("Object type of val is " + o); // 119
    }
}

ผลลัพธ์

Value of x is 119
Value type of val is 120
Object type of val is 119

คำอธิบาย: Boxing เก็บค่า 119 ไว้ใน object o แล้ว val เปลี่ยนเป็น 120 Unboxing ดึงค่าจาก o ได้ 119 (ค่าเดิม) แสดงว่า Boxing สร้าง copy ใหม่ใน Heap