跳转到内容

C Sharp 类型参数协变与逆变

来自代码酷

C#类型参数协变与逆变[编辑 | 编辑源代码]

介绍[编辑 | 编辑源代码]

在C#中,协变(Covariance)逆变(Contravariance)是泛型类型参数的两个重要概念,它们允许在泛型类型之间进行更灵活的转换。协变和逆变主要用于接口和委托,使得类型参数可以更自然地适应继承关系。

  • 协变:允许使用比原始类型更具体的派生类型(子类)。例如,如果 `IEnumerable<Derived>` 可以赋值给 `IEnumerable<Base>`,则称 `IEnumerable<T>` 是协变的。
  • 逆变:允许使用比原始类型更通用的基类型(父类)。例如,如果 `Action<Base>` 可以赋值给 `Action<Derived>`,则称 `Action<T>` 是逆变的。

C# 4.0 引入了对泛型接口和委托的协变和逆变支持,通过 `out` 和 `in` 关键字分别标记协变和逆变类型参数。

协变(Covariance)[编辑 | 编辑源代码]

协变允许泛型类型参数从派生类向基类转换。在C#中,协变通过 `out` 关键字标记。

示例:协变接口[编辑 | 编辑源代码]

以下是一个协变接口 `IEnumerable<T>` 的示例:

using System;
using System.Collections.Generic;

class Animal { public string Name { get; set; } }
class Dog : Animal { }

class Program
{
    static void Main()
    {
        IEnumerable<Dog> dogs = new List<Dog> { new Dog { Name = "Buddy" } };
        IEnumerable<Animal> animals = dogs; // 协变:IEnumerable<Dog> 转换为 IEnumerable<Animal>

        foreach (var animal in animals)
        {
            Console.WriteLine(animal.Name);
        }
    }
}

输出:

Buddy

解释:

  • `IEnumerable<T>` 是协变的,因为它的类型参数标记为 `out`。
  • 可以将 `IEnumerable<Dog>` 赋值给 `IEnumerable<Animal>`,因为 `Dog` 是 `Animal` 的子类。

协变类型参数的限制[编辑 | 编辑源代码]

协变类型参数 (`out`) 只能用于方法的返回类型,不能用于方法的输入参数。例如:

interface ICovariant<out T>
{
    T GetItem(); // 合法:T 是返回类型
    // void SetItem(T item); // 非法:T 不能作为输入参数
}

逆变(Contravariance)[编辑 | 编辑源代码]

逆变允许泛型类型参数从基类向派生类转换。在C#中,逆变通过 `in` 关键字标记。

示例:逆变接口[编辑 | 编辑源代码]

以下是一个逆变接口 `IComparer<T>` 的示例:

using System;
using System.Collections.Generic;

class Animal { public string Name { get; set; } }
class Dog : Animal { }

class AnimalComparer : IComparer<Animal>
{
    public int Compare(Animal x, Animal y) => x.Name.CompareTo(y.Name);
}

class Program
{
    static void Main()
    {
        IComparer<Animal> animalComparer = new AnimalComparer();
        IComparer<Dog> dogComparer = animalComparer; // 逆变:IComparer<Animal> 转换为 IComparer<Dog>

        var dog1 = new Dog { Name = "Buddy" };
        var dog2 = new Dog { Name = "Max" };
        Console.WriteLine(dogComparer.Compare(dog1, dog2));
    }
}

输出:

-1

解释:

  • `IComparer<T>` 是逆变的,因为它的类型参数标记为 `in`。
  • 可以将 `IComparer<Animal>` 赋值给 `IComparer<Dog>`,因为 `Animal` 是 `Dog` 的基类。

逆变类型参数的限制[编辑 | 编辑源代码]

逆变类型参数 (`in`) 只能用于方法的输入参数,不能用于方法的返回类型。例如:

interface IContravariant<in T>
{
    void Process(T item); // 合法:T 是输入参数
    // T GetResult(); // 非法:T 不能作为返回类型
}

协变与逆变的对比[编辑 | 编辑源代码]

以下表格总结了协变和逆变的关键区别:

特性 协变 (`out`) 逆变 (`in`)
关键字 `out` `in`
方向 派生类 → 基类 基类 → 派生类
用途 返回类型 输入参数

实际应用场景[编辑 | 编辑源代码]

场景1:集合的协变转换[编辑 | 编辑源代码]

协变常用于集合接口(如 `IEnumerable<T>`),使得可以统一处理不同派生类型的集合。

IEnumerable<string> strings = new List<string> { "a", "b", "c" };
IEnumerable<object> objects = strings; // 协变转换

场景2:委托的逆变[编辑 | 编辑源代码]

逆变常用于委托(如 `Action<T>`),使得可以传递更通用的方法。

Action<object> logObject = obj => Console.WriteLine(obj);
Action<string> logString = logObject; // 逆变转换
logString("Hello"); // 输出:Hello

图表说明[编辑 | 编辑源代码]

以下是一个Mermaid图表,展示协变和逆变的类型转换关系:

classDiagram class Animal class Dog : Animal Animal <|-- Dog note for Animal "协变:IEnumerable<Dog> → IEnumerable<Animal>" note for Dog "逆变:Action<Animal> → Action<Dog>"

数学表示[编辑 | 编辑源代码]

协变和逆变可以用数学符号表示:

  • 协变:若 `A ≤ B`,则 `F<A> ≤ F`(`F` 是协变类型构造器)。
  • 逆变:若 `A ≤ B`,则 `F ≤ F<A>`(`F` 是逆变类型构造器)。

解析失败 (语法错误): {\displaystyle \text{协变:} \quad A \leq B \implies F<A> \leq F<B> \\ \text{逆变:} \quad A \leq B \implies F<B> \leq F<A> }

总结[编辑 | 编辑源代码]

  • 协变 (`out`) 允许从派生类向基类转换,适用于返回类型。
  • 逆变 (`in`) 允许从基类向派生类转换,适用于输入参数。
  • 协变和逆变提高了泛型类型的灵活性,尤其在集合和委托中非常有用。