我都此类工作作为我的仓库:具有非泛型方法约束的泛型类?
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() { }
}
}
这使得Repository模板类无效,因为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()'约束呢? – 2014-11-05 12:44:51
@dav_i由于'GetByID'和其他类似的'Get'方法,我创建了一个T的新实例,填充它的数据并返回它。 – Danicco 2014-11-05 12:46:15
无法达到此目的,但也可以使用类似AutoMapper的库,并允许实施存储库,以确定如何将原始数据从存储库转换为要传递给自动映射器的数据传输对象。 – 2014-11-05 12:56:55