本文介绍了分配IEnumerable(协方差)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 IEnumerable 在C#4.0中有一个协变参数,我很困惑它在下面的代码中的行为。

Since IEnumerable has a covariant parameter in C# 4.0 I am confused how it is behaving in the following code.

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 c $ c> DoTestTwo 。除了为什么它不工作,如果任何人知道我如何可以实现 DoTestOne (分配 IEnumberable< H>的效果,其中H:

So basically the DoTestOne method doesn't compile while DoTestTwo does. In addition to why it doesn't work, if anyone knows how I can achieve the effect of DoTestOne (assigning an IEnumberable<H> where H : IFoo to an IEnumberable<IFoo>) I would appreciate the help.

推荐答案

如果你知道H将是一个类,这工作:

If you know that H will be a class, this does work:

    public void DoTestOne<H>(IEnumerable<H> bars) where H : class, IFoo
    {
        foos = bars;
    }

这里的问题是如果H是值类型,协方差不是因为 IEnumerable< MyStruct> 实际上返回值类型,而 IEnumerable< IFoo> 返回盒子实例。如有必要,您可以使用明确的 Cast< IFoo> 解决此问题。

The issue here is that if H is a value type, the covariance is not exactly what you'd expect, as IEnumerable<MyStruct> actually returns the value types whereas IEnumerable<IFoo> has to return boxed instances. You can use an explicit Cast<IFoo> to get around this, if necessary.

这篇关于分配IEnumerable(协方差)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 04:41