gpt4 book ai didi

c# - 接口(interface)声明为 IEnumerable 但不能这样使用

转载 作者:行者123 更新时间:2023-11-30 16:18:47 25 4
gpt4 key购买 nike

我有一个 IEnumerable 接口(interface):

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。你知道怎么做吗?如果我尝试这样做,它会提示在 IEnumerable 中转换 IBrands。

谢谢!

最佳答案

IBrands 是一个 IEnumerable<IBrand> ,但反之则不然。所以你不能返回 IEnumerable<IBrand>作为 IBrand。

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

return new Brands(_carsDic.Values);

关于c# - 接口(interface)声明为 IEnumerable 但不能这样使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15875905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com