c# - 您能否通过使用 List<T> 来满足具有 IEnumerable<T> 的接口(interface)?

标签 c# inheritance

假设我有以下模型:

public interface IProduct
{
    IEnumerable<Ingredient> Ingredients { get; set; }
}

public class Product : IProduct
{
    public IEnumerable<Ingredient> Ingredients { get; set; }
}

public class Ingredient
{
}

但我想要Ingredients成为List<Ingredient>而不是 IEnumerable<Ingredient>

有没有办法对接口(interface)进行建模以接受IEnumerable<T>List<T>

我尝试了以下方法。但是当然,语法不支持这个并且看不到 TEnumerable<Ingredient>作为通用参数。

public interface IProduct<TEnumerable<Ingredient>> 
    where TEnumerable<Ingredient> : IEnumerable<Ingredient>
{
    TEnumerable<Ingredient> Ingredients { get; set; }
}

public class Product : IProduct
{
    public List<Ingredient> Ingredients { get; set; }
}

public class Ingredient
{
}

我意识到这不是很实用,但我只是怀着好奇的心情看着它。

最佳答案

你的语法有点不对:

  • 您不能像这样以通用方式声明类型参数
  • 你的 Product type 在说明其如何实现时需要指定类型参数 IProduct<TEnumerable>

所以这是有效的:

public interface IProduct<TEnumerable> 
    where TEnumerable : IEnumerable<Ingredient>
{
    TEnumerable Ingredients { get; set; }
}

public class Product : IProduct<List<Ingredient>>
{
    public List<Ingredient> Ingredients { get; set; }
}

它可能不会有帮助,但至少它是有效的...

关于c# - 您能否通过使用 List<T> 来满足具有 IEnumerable<T> 的接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19068971/

相关文章:

c# - 无法从 GetCustomAttributes 取回属性

c# - Windows 身份基础 - 注销或更新声明

java - 创建另一个子类java的构造函数

Javascript __proto__ 输出

c# - 如何阻止自定义性能计数器实例名称自动转换为小写

c# - 在 .net 中设置 post 参数的等效方法是什么?

c# - 使用 Entity Framework 对接口(interface)进行编码

c# - 如何在 C# 中编写泛型方法及其默认等效项

java - 生成器模式和继承

python - Django中的继承: child class updates parent with empty fields