【发布时间】:2011-10-20 00:34:43
【问题描述】:
我有一个示例程序,它有一个基本的 Fruit 类和一个派生的 Apple 类。
class Testy
{
public delegate void FruitDelegate<T>(T o) where T : Fruit;
private List<FruitDelegate<Fruit>> fruits = new List<FruitDelegate<Fruit>>();
public void Test()
{
FruitDelegate<Apple> f = new FruitDelegate<Apple>(EatFruit);
fruits.Add(f); // Error on this line
}
public void EatFruit(Fruit apple) { }
}
我想要一个水果代表列表,并能够将更多派生水果的代表添加到列表中。我相信这与协变或逆变有关,但我似乎无法弄清楚。
错误信息是(没有命名空间):
The best overloaded method match for 'List<FruitDelegate<Fruit>>.Add(FruitDelegate<Fruit>)' has some invalid arguments`
【问题讨论】:
标签: c# generics delegates covariance contravariance