【发布时间】:2014-02-06 17:27:54
【问题描述】:
我目前正在学习位于here 的 .NET Web API 教程。在示例中,我们在模型类中定义了一个接口,如下所示:
namespace ProductStore.Models
{
public interface IProductRepository
{
IEnumerable<Product> GetAll();
Product Get(int id);
Product Add(Product item);
void Remove(int id);
bool Update(Product item);
}
}
然后,在本教程的后面,我们这样实现这个接口:
namespace ProductStore.Models
{
public class ProductRepository : IProductRepository
{
private List<Product> products = new List<Product>();
private int _nextId = 1;
public ProductRepository()
{
Add(new Product { Name = "Tomato soup", Category = "Groceries", Price = 1.39M });
Add(new Product { Name = "Yo-yo", Category = "Toys", Price = 3.75M });
Add(new Product { Name = "Hammer", Category = "Hardware", Price = 16.99M });
}
public IEnumerable<Product> GetAll()
{
return products;
}
public Product Get(int id)
{
return products.Find(p => p.Id == id);
}
public Product Add(Product item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
item.Id = _nextId++;
products.Add(item);
return item;
}
public void Remove(int id)
{
products.RemoveAll(p => p.Id == id);
}
public bool Update(Product item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
int index = products.FindIndex(p => p.Id == item.Id);
if (index == -1)
{
return false;
}
products.RemoveAt(index);
products.Add(item);
return true;
}
}
}
我的问题是,如果实现要专门在List<Product> 上运行,为什么要编写接口以使GetAll() 返回IEnumerable<Product>?
我假设这是为了促进重用,以便其他一些IProductRepository 实现可以使用不同的IEnumerable<Product>(尽管这样的例子很好,因为我想不出一个,并不是我怀疑它存在,我只是经验不足)。
假设重用确实是目标,那么为什么要这样写实现:
public IEnumerable<Product> GetAll()
{
return products;
}
而不是这样:
public List<Product> GetAll()
{
return products;
}
框架或编译器是否无法看到public List<Product> GetAll() 可从public IEnumerable<Product> GetAll() 派生?
【问题讨论】:
-
因为这意味着您将来可以将其更改为
List<T>以外的其他内容,而不会破坏接口契约。
标签: c# asp.net asp.net-web-api ienumerable