Covariance and Contravariance in Delegates
posted on 01 Oct 2006 01:05 by tidno1 in csharp-and-dotnet
คงเคยใช้ delegate กันมาบ้างใช่มั้ยครับ ลองมารู้จักกับศัพท์แปลก ๆ กันซักสองคำ
Covariance
covariance คือการที่ return type ของ method นั้น specific มากกว่า (derive มาจาก) return type ของ delegate นั้น
class Shape { }
class Polygon : Shape { }
class Program {
public delegate Shape ConstructCallback();
public Shape Construct1() {...}
public Polygon Construct2() {...}
static void Main() {
ConstructCallback handler1 = Construct1;
// Covariance allows this delegate.
ConstructCallback handler2 = Construct2;
}
}
class Polygon : Shape { }
class Program {
public delegate Shape ConstructCallback();
public Shape Construct1() {...}
public Polygon Construct2() {...}
static void Main() {
ConstructCallback handler1 = Construct1;
// Covariance allows this delegate.
ConstructCallback handler2 = Construct2;
}
}
Contravariance
contravariance คือการที่ method มี parameter ที่เป็น base type ของ parameter ใน delegate ตัวนั้น ๆ
class Shape { }
class Polygon : Shape { }
class Program {
public delegate void RenderCallback(Polygon);
public void Render1(Shape s) {...}
public void Render2(Polygon p) {...}
static void Main() {
// Contravariance permits this delegate.
RenderCallback handler1 = Render1;
RenderCallback handler2 = Render2;
}
}
class Polygon : Shape { }
class Program {
public delegate void RenderCallback(Polygon);
public void Render1(Shape s) {...}
public void Render2(Polygon p) {...}
static void Main() {
// Contravariance permits this delegate.
RenderCallback handler1 = Render1;
RenderCallback handler2 = Render2;
}
}
อิอิ ไว้ว่างๆ จะมาตามเก็บนะ ^^
#1 By #G~nap# on 2006-10-01 22:22