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

Value Type vs Reference Type ใน C#

Value Type (ชนิดค่า)

  • เก็บข้อมูลโดยตรง (Contains data directly)
  • มาจาก System.ValueType
  • จัดเก็บใน Stack
  • ตัวอย่าง: int, char, float, double, bool, struct, enum
  • การกำหนดค่า = คัดลอกข้อมูล (Copy by value)

Reference Type (ชนิดอ้างอิง)

  • เก็บที่อยู่หน่วยความจำ (Reference to memory location)
  • จัดเก็บใน Heap
  • ตัวแปรหลายตัวอาจชี้ไปที่ข้อมูลเดียวกัน
  • ตัวอย่าง: class, string, array, delegate, object, dynamic
  • การกำหนดค่า = คัดลอก Reference (Copy by reference)

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

คุณสมบัติValue TypeReference Type
เก็บในStackHeap
ค่าเริ่มต้น0, false, '\0'null
การกำหนดค่าCopy valueCopy reference
Null ได้ไหมไม่ได้ (ยกเว้น Nullable)ได้
Destructionทันทีเมื่อออก ScopeGarbage Collector

ตัวอย่างพฤติกรรม

// Value Type
int a = 10;
int b = a;
b = 20;
Console.WriteLine(a); // 10 (ไม่เปลี่ยน)

// Reference Type
int[] arr1 = {1, 2, 3};
int[] arr2 = arr1;
arr2[0] = 99;
Console.WriteLine(arr1[0]); // 99 (เปลี่ยนเพราะชี้ที่เดียวกัน)