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

Covariance และ Contravariance ใน C#

Covariance และ Contravariance เป็นแนวคิดในการจัดการความสัมพันธ์ระหว่างประเภทข้อมูล (Type Relationships) ใน C# ช่วยให้เขียนโค้ดที่ยืดหยุ่นและปลอดภัยทางประเภท (Type-safe) ได้มากขึ้น

ลำดับชั้นคลาสตัวอย่าง

class One { }
class Two : One { }
class Three : Two { }

Covariance (ความแปรผันร่วม)

อนุญาตให้ใช้ประเภทลูก (Derived Type) แทนประเภทแม่ (Base Type) ได้

  • ใช้กับ: อาร์เรย์, อินเทอร์เฟซ Generic (out), Delegate (return type)
  • ตัวอย่าง: IEnumerable<Two> สามารถมอบหมายให้ IEnumerable<One> ได้

Contravariance (ความแปรผันตรงข้าม)

อนุญาตให้ใช้ประเภทแม่ แทนประเภทลูก ได้ในตำแหน่งพารามิเตอร์ (Input)

  • ใช้กับ: อินเทอร์เฟซ Generic (in), Delegate (parameter types)
  • ตัวอย่าง: Action<One> สามารถมอบหมายให้ Action<Two> ได้

ตัวอย่าง Delegate

// Covariance: Return type
delegate One Factory();
Factory f1 = () => new Two(); // OK - Two คือ One

// Contravariance: Parameter type
delegate void Processor(Two t);
Processor p1 = (One o) => { }; // OK - One รับ Two ได้

สรุป: "Out" = Covariance (ส่งออก/Return) | "In" = Contravariance (รับเข้า/Parameter)