VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > c#编程 >
  • C#中泛型接口的协变和抗变

在 C# 中,我们可以使用泛型接口来实现协变(covariance)和逆变(contravariance)。协变允许我们将一个泛型接口的类型参数从派生类传递给基类,而逆变则允许我们将一个泛型接口的类型参数从基类传递给派生类。以下是一个示例代码,演示了协变和逆变的使用:
using System;
using System.Collections.Generic;
 
public interface IAnimal
{
    void MakeSound();
}
 
public class Dog : IAnimal
{
    public void MakeSound()
    {
        Console.WriteLine("Woof!");
    }
}
 
public class Cat : IAnimal
{
    public void MakeSound()
    {
        Console.WriteLine("Meow!");
    }
}
 
public interface IAnimalShelter<out T>
{
    T GetAnimal();
}
 
public class DogShelter : IAnimalShelter<Dog>
{
    public Dog GetAnimal()
    {
        return new Dog();
    }
}
 
public class AnimalSoundPlayer<in T>
{
    public void PlaySound(T animal)
    {
        animal.MakeSound();
    }
}
 
public class Program
{
    public static void Main(string[] args)
    {
        IAnimalShelter<IAnimal> shelter = new DogShelter();
        IAnimal dog = shelter.GetAnimal();
        dog.MakeSound();  // 输出: Woof!
 
        AnimalSoundPlayer<Dog> soundPlayer = new AnimalSoundPlayer<Dog>();
        soundPlayer.PlaySound(new Dog());  // 输出: Woof!
    }
}

 
在上面的示例中,我们定义了一个 IAnimal 接口和两个实现类 Dog 和 Cat。然后,我们定义了一个泛型接口 IAnimalShelter<out T>,使用 out 关键字使其支持协变。接着,我们创建了一个 DogShelter 类来实现这个泛型接口,并实现了 GetAnimal 方法来返回一个 Dog 对象。
接下来,我们定义了一个泛型类 AnimalSoundPlayer<in T>,使用 in 关键字使其支持逆变。在这个类中,我们定义了一个 PlaySound 方法,该方法接受一个 T 类型的参数,并调用了该类型的 MakeSound 方法。
在 Main 方法中,我们创建了一个 DogShelter 对象并将其赋值给 IAnimalShelter<IAnimal> 类型的变量。然后,我们调用 GetAnimal 方法来获取一个 IAnimal 对象,并调用其 MakeSound 方法来输出声音。
接着,我们创建了一个 AnimalSoundPlayer<Dog> 对象,并调用其 PlaySound 方法,传入一个 Dog 对象。在 PlaySound 方法内部,我们调用了 Dog 对象的 MakeSound 方法来输出声音。
通过协变和逆变,我们可以更灵活地使用泛型接口,并实现对泛型类型参数的类型转换。这使得我们能够在泛型代码中更好地适应不同的类型。


最后,如果你对python语言还有任何疑问或者需要进一步的帮助,请访问https://www.xin3721.com 本站原创,转载请注明出处:https://www.xin3721.com/ArticlecSharp/c47996.html

相关教程