【发布时间】:2014-11-05 21:11:22
【问题描述】:
我有这个类作为我的存储库:
public class Repository<T> where T : class, new()
{
public T GetByID(int id)
{
//Code...
}
}
但在某些情况下,我不想保留类的默认公共构造函数(例如一些需要一些逻辑的特定模型属性),如下所示:
public class Person
{
public CPersonID PersonID { get; private set; }
//This shouldn't exist outside Person, and only Person knows the rules how to handle this
public class CPersonID
{
internal CPersonID() { }
}
}
由于new() 约束,这使得存储库模板类无效。
我想做这样的事情:
public class Repository<T> where T : class
{
//This function should be created only when the T has new()
public GetByID(int id) where T : new()
{
}
//And this could be the alternative if it doesn't have new()
public GetByID(T element, int id)
{
}
}
有什么办法可以做到吗?
编辑:Get 方法示例:
public IList<T> GetAll()
{
IList<T> list = new List<T>();
using(IConnection cn = ConnectionFactory.GetConnection())
{
ICommand cm = cn.GetCommand();
cm.CommandText = "Query";
using (IDataReader dr = cm.ExecuteReader())
{
while(dr.Read())
{
T obj = new T(); //because of this line the class won't compile if I don't have the new() constraint
//a mapping function I made to fill it's properties
LoadObj(obj, dr);
list.Add(obj);
}
}
}
return list;
}
【问题讨论】:
-
为什么
Repository需要有new()约束? -
@dav_i 因为
GetByID和其他类似的Get方法,我创建了一个新的T 实例,填充它的数据,然后返回它。 -
您无法以您想要的方式实现这一点,但是您也可以使用 AutoMapper 之类的库,并允许存储库的实现确定如何将存储库中的原始数据转换为数据传输对象传递给自动映射器。
标签: c# generics type-constraints