在 C# 中,使用 in 关键字可以指定逆变性。以下是一个示例,展示如何使用逆变性和泛型接口来处理多个类型的生产者。
逆变性
using System;
// 定义逆变的泛型接口
public interface IProducer<in T>
{
void Produce(T item);
}
// 实现生产者类
public class FruitProducer : IProducer<Fruit>
{
public void Produce(Fruit fruit)
{
Console.WriteLine($"Produced a fruit: {fruit.Name}");
}
}
public class AppleProducer : IProducer<Apple>
{
public void Produce(Apple apple)
{
Console.WriteLine($"Produced an apple: {apple.Name}");
}
}
// 基类和子类
public class Fruit
{
public string Name { get; }
public Fruit(string name)
{
Name = name;
}
}
public class Apple : Fruit
{
public Apple(string name) : base(name) { }
}
// 主程序
class Program
{
static void Main()
{
// 创建生产者实例
IProducer<Fruit> fruitProducer = new FruitProducer();
IProducer<Apple> appleProducer = new AppleProducer();
// 创建水果和苹果
Fruit fruit = new Fruit("Banana");
Apple apple = new Apple("Granny Smith");
// 使用生产者
fruitProducer.Produce(fruit);
appleProducer.Produce(apple);
// 使用逆变
IProducer<Fruit> fruitProducerFromApple = appleProducer;
fruitProducerFromApple.Produce(new Apple("Honeycrisp"));
}
}
逆变性+委托
using System;
// 定义逆变的泛型委托
public delegate void ProducerDelegate<in T>(T item);
// 定义逆变的泛型接口
public interface IProducer<in T>
{
void Produce(T item);
}
// 实现生产者类
public class FruitProducer : IProducer<Fruit>
{
public void Produce(Fruit fruit)
{
Console.WriteLine($"Produced a fruit: {fruit.Name}");
}
}
public class AppleProducer : IProducer<Apple>
{
public void Produce(Apple apple)
{
Console.WriteLine($"Produced an apple: {apple.Name}");
}
}
// 基类和子类
public class Fruit
{
public string Name { get; }
public Fruit(string name)
{
Name = name;
}
}
public class Apple : Fruit
{
public Apple(string name) : base(name) { }
}
// 主程序
class Program
{
static void Main()
{
// 创建生产者实例
IProducer<Fruit> fruitProducer = new FruitProducer();
IProducer<Apple> appleProducer = new AppleProducer();
// 创建委托实例
ProducerDelegate<Fruit> fruitDelegate = fruitProducer.Produce;
ProducerDelegate<Apple> appleDelegate = appleProducer.Produce;
// 创建水果和苹果
Fruit fruit = new Fruit("Banana");
Apple apple = new Apple("Granny Smith");
// 使用委托生产水果和苹果
fruitDelegate(fruit);
appleDelegate(apple);
// 使用逆变
ProducerDelegate<Fruit> fruitDelegateFromApple = appleProducer.Produce;
fruitDelegateFromApple(new Apple("Honeycrisp"));
}
}