C#

微软msdn对协变和逆变的定义如下:

将方法签名与委托类型匹配时,协变和逆变为您提供了一定程度的灵活性。协变允许方法具有的派生返回类型比委托中定义的更多。逆变允许方法具有的派生参数类型比委托类型中的更少。

用代码来理解下

using System;

namespace ConsoleApp1

{

class Program

{

class Human { }

class Student : Human { }

class Teacher : Human { }

delegate Human HumanDelegate();

static Teacher TestMethod1()

{

return new Teacher();

}

static Student TestMethod2()

{

return new Student();

}

static void Main(string[] args)

{

HumanDelegate hd = TestMethod1;

HumanDelegate hd2 = TestMethod2;

Console.WriteLine(hd.Invoke().GetType());

Console.WriteLine(hd2.Invoke().GetType().ToString());

Console.Read();

}

}

}

上面代码定义了一个返回类型为Human的委托,两个返回类型继承于Human的普通方法,也就是说,协变允许普通方法具有的返回类型比委托中的返回类型更多。

原文地址:https://www.cnblogs.com/tcli/p/6661799.html