【问题标题】:Interface declared as IEnumerable but not usable as such接口声明为 IEnumerable 但不能这样使用
【发布时间】:2013-04-08 09:40:17
【问题描述】:

我有一个 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 中的铸造。

谢谢!

【问题讨论】:

  • 检查SelectMany返回的内容,可能是IEnumerable&lt;IEnumerable&lt;IBrand&gt;&gt;
  • 你能告诉我们确切的错误信息吗?而_carsDic的声明又是什么?
  • 错误:“无法将表达式类型 'SystemC.Collections.Generic.List' 转换为返回类型 'Interfaces.Ibrands'”

标签: c# casting ienumerable


【解决方案1】:

IBrands 是IEnumerable&lt;IBrand&gt;,但反之则不然。因此,您不能将 IEnumerable&lt;IBrand&gt; 作为 Ibrands 返回。

根据 Brands 实际代表的内容,您可以创建另一个 Brands 实例。

return new Brands(_carsDic.Values);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-20
    相关资源
    最近更新 更多