【发布时间】:2012-09-08 02:31:23
【问题描述】:
可能重复:
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)
{ }
}
代码中标记为“这不起作用”的两行将无法编译。
我可以解决这个问题,但我的意图似乎没有错。或者,是吗?
【问题讨论】:
-
这个问题被问得太频繁了,有太多不同的变体。我们需要一个“协方差在 C# 中不能以这种方式工作”的关闭原因:)
-
我比其他问题更喜欢我的问题! (我也非常喜欢和感谢 Thomas 和 ie 的回答。)
标签: c#