委托的协变与逆变
★ 协变:
委托的类型返回值是它所指向函数的返回值得基类.
委托的类型返回值是它所指向函数的返回值得基类.
private void InitPage()
{
HandlerMethod handler1 = Method1;
HandlerMethod handler2 = Method2; // 协变
}
private class Animal { }
private class Dog : Animal { }
private delegate Animal HandlerMethod();
private static Animal Method1() { return null; }
private static Dog Method2() { return null; }
{
HandlerMethod handler1 = Method1;
HandlerMethod handler2 = Method2; // 协变
}
private class Animal { }
private class Dog : Animal { }
private delegate Animal HandlerMethod();
private static Animal Method1() { return null; }
private static Dog Method2() { return null; }
★ 逆变:
委托的类型参数是它所指向函数的参数的派生类.
private void InitPage()
{
HandlerMethod handler1 = Method1;
HandlerMethod handler2 = Method2; // 逆变
}
private class Animal { }
private class Dog : Animal { }
private delegate void HandlerMethod(Dog dog);
private static void Method1(Dog dog) { }
private static void Method2(Animal animal) { }
{
HandlerMethod handler1 = Method1;
HandlerMethod handler2 = Method2; // 逆变
}
private class Animal { }
private class Dog : Animal { }
private delegate void HandlerMethod(Dog dog);
private static void Method1(Dog dog) { }
private static void Method2(Animal animal) { }