【发布时间】:2012-10-18 19:37:06
【问题描述】:
由于IEnumerable 在 C# 4.0 中有一个协变参数,我对它在以下代码中的行为感到困惑。
public class Test
{
IEnumerable<IFoo> foos;
public void DoTestOne<H>(IEnumerable<H> bars) where H : IFoo
{
foos = bars;
}
public void DoTestTwo(IEnumerable<IBar> bars)
{
foos = bars;
}
}
public interface IFoo
{
}
public interface IBar : IFoo
{
}
所以基本上DoTestOne 方法不能编译,而DoTestTwo 可以。除了为什么不起作用之外,如果有人知道我如何实现DoTestOne 的效果(将IEnumberable<H> where H : IFoo 分配给IEnumberable<IFoo>),我将不胜感激。
【问题讨论】:
标签: c# c#-4.0 ienumerable covariance