假设我有以下模型:
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/