3

我有一个 IEnumerable 接口:

public interface IBrands: IEnumerable<Ibrand>

及其实例:

public class Brands: IBrands
{
    public Brands()
    {
        _brandsDic= new Dictionary<int, IBrand>();
    }
}

当我使用 Linq 在另一个类中检索一些数据时,我必须返回一些 IEnumerable:

public IEnumerable<IBrand> GetCarsBrands()
{
    return _carsDic.SelectMany(r => r.Value.Brands).ToList();
}

...但想直接返回一个 IBrands。你知道怎么做吗?如果我尝试这样做,它会抱怨 Ibrands 在 IEnumerable 中的铸造。

谢谢!

4

1 回答 1

3

The IBrands is an IEnumerable<IBrand>, but not the other way around. So you can't return an IEnumerable<IBrand> as IBrands.

Depending of what Brands actually represents, you could create another instance of Brands.

return new Brands(_carsDic.Values);
于 2013-04-08T09:46:59.250 回答