在编程语言中,“协变”是指能够使用与原始指定的派生类型相比,派生程度更大的类型。
“逆变”则是指能够使用派生程度更小的类型。

在 .NET Framework 4 和 Visual Studio 2010 中,C# 和 Visual Basic 都支持在泛型接口和委托中使用协变和逆变,并允许隐式转换泛型类型参数。

 

C# 和 Visual Basic 都允许您创建自己的变体接口和委托。

这样,您不仅可以为委托指派具有匹配签名的方法,而且可以指派这样的方法:它们返回与委托类型指定的派生类型相比,派生程度更大的类型(协变),或者接受相比之下,派生程度更小的类型的参数(逆变)。

实例

  1. 首先定义一个接口IColor及两个派生类
    public interface IColor { }

    public class Red : IColor { }

    public class Blue : IColor { } 
  2. 定义ColorDemo类用来写展示协变与逆变的逻辑
     
      public class ColorDemo{}
  3. 编写具体实现
    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);
    }

    }

相关文章:

  • 2021-08-31
  • 2021-05-22
  • 2021-06-04
  • 2021-10-20
  • 2022-12-23
  • 2021-11-27
  • 2021-06-08
  • 2022-02-11
猜你喜欢
  • 2021-09-17
  • 2021-08-10
  • 2021-09-24
  • 2022-12-23
  • 2021-09-28
  • 2022-12-23
  • 2021-11-19
相关资源
相似解决方案