可能重复的:
Casting List<> of Derived class to List<> of base class通用型一类的不能接受泛型类型派生类型的类
标题可能不会是很有意义的。请参阅代码:
class Person {}
class Manager : Person {}
class PaymentCalculator<T> where T : Person
{
public double Calculate(T person)
{
return 0; // calculate and return
}
}
class Calculators : List<PaymentCalculator<Person>>
{
public Calculators()
{
this.Add(new PaymentCalculator<Person>());
this.Add(new PaymentCalculator<Manager>()); // this doesn't work
PassCalculator(new PaymentCalculator<Person>());
PassCalculator(new PaymentCalculator<Manager>()); // this doesn't work
}
public void PassCalculator(PaymentCalculator<Person> x)
{ }
}
代码中标记为“this does not work”的两行不会编译。
我可以解决这个问题,但似乎我的意图不是错误的。或者,是吗?
这个问题太频繁地以太多的方式被问到。我们需要一个“协方差在C#中不能这样工作”的关闭原因:) –
我比另一个问题更喜欢我的问题! (也是我真的很喜欢和欣赏托马斯和ie的答案) – kennethc