百度百科逆变的概念,再来练下对逆变的理解。
在下面的示例代码中,定义三个委托方法,一个普通方法
委托方法的签名参数继承于Human,普通方法的参数是父类。
因此,在调用委托时,可把子类转换为父类。
这样可以使我们的普通方法更具通用性。
using System;
namespace ConsoleApp1
{
class Human { }
class Student : Human { }
class Teacher : Human { }
class Program
{
public delegate void StudentDelegate(Student stu);
public delegate void TeacherDelegate(Teacher tea);
public delegate void HumanDelegate(Human h);
public static void TestHandler(Human human)
{
Console.WriteLine("This is class :{0}", human.GetType());
}
public static void StudentHandler(Student human)
{
Console.WriteLine("This is class :{0}", human.GetType());
}
static void Main(string[] args)
{
Console.WriteLine("input any key to start.");
Console.Read();
StudentDelegate handler1 = TestHandler;
TeacherDelegate handler2 = TestHandler;
HumanDelegate handler3 = TestHandler;
handler1.Invoke(new Student());
handler2.Invoke(new Teacher());
handler3.Invoke(new Human());
Console.Read();
}
}
}