【发布时间】:2012-07-30 04:13:23
【问题描述】:
泛型类和依赖注入有什么区别吗? 难道它们不是实现控制反转的方法吗
泛型类不是实现依赖注入并增加编译时安全性的方法吗?
例如,如果我有一个节点类,那么我可以定义如下
class Node<T> where T : ISomeInterface
{
..
..
}
class Node
{
ISomeInterface obj
public Node(ISomeInterface inject)
{
obj = inject;
}
}
更新 2 有新的
class Node<T> where T : ISomeInterface, new()
{
ISomeInterface obj
public Node()
{
obj = new T();
}
}
更新 3 @akim:我做了你要求使用泛型的例子 使用泛型的存储库
Interface IRepository
{
public DataTable GetAll();
}
public class ProductRep : IRepository
{
public DataTable GetAll()
{
//implementation
}
}
public class MockProductRep : IRepository
{
public DataTable GetAll()
{
//mock implementation
}
}
public class Product<T> where T : IRepository, new()
{
IRepository repository = null
public Product()
{
repository = new T();
}
public List<Product> GetProduct()
{
DataTable prodlst = repository.GetAll();
//convert to List of products now
}
}
//so while using the Product class, client would Supply ProductRep class and in NUnit you //would supply MockProductRep class
Product<ProductRep> obj = new ProductRep<ProductRep>();
List<Product> lst = obj.GetProduct();
//in NUnit
Product<MockProductRep> obj = new ProductRep<MockProductRep>();
List<Product> lst = obj.GetProduct();
【问题讨论】:
-
如果您投反对票,请考虑添加 cmets 说明您投反对票的原因。
-
有人说服你“泛型方法”是一种不好的做法吗?我不相信该主题的答案,因为 IoC 相对于“泛型方法”的好处仅与后期绑定有关。但大多数应用程序不需要此功能。那么,阿南德,你现在有什么看法?
标签: c# design-patterns generics dependency-injection