在编程语言中,“协变”是指能够使用与原始指定的派生类型相比,派生程度更大的类型。“逆变”则是指能够使用派生程度更小的类型。
实例
public interface IColor { }
public class Red : IColor { }
public class Blue : IColor { }
public class ColorDemo{}
public class ColorDemo
{
// 协变委托
private delegate T CovarianceDelegate < out T > ();
// 逆变委托
private delegate void ContravarianceDelegate < in T > (T color);
private static string colorInfo;
public void CoreMethod()
{
// 协变
CovarianceDelegate < IColor > a1 = ColorMethod;
a1.Invoke();
CovarianceDelegate < Red > a2 = RedMethod;
a2.Invoke();
a1 = a2;
a1.Invoke();
// 逆变
ContravarianceDelegate < Blue > b1 = BlueMethod;
b1.Invoke( new Blue());
ContravarianceDelegate < IColor > b2 = ColorMethod;
b2.Invoke( new Red());
b1 = b2;
b1.Invoke( new Blue());
}
private IColor ColorMethod()
{
colorInfo = " 无色 " ;
Console.WriteLine(colorInfo);
return null ;
}
private void ColorMethod(IColor color)
{
colorInfo = " 无色 " ;
Console.WriteLine(colorInfo);
}
private Red RedMethod()
{
colorInfo = " 红色 " ;
Console.WriteLine(colorInfo);
return new Red();
}
private void BlueMethod(Blue blue)
{
colorInfo = " 蓝色 " ;
Console.WriteLine(colorInfo);
}
}
static void Main( string [] args)
{
ColorDemo colorDemo = new ColorDemo();
colorDemo.CoreMethod();
Console.ReadLine();
}