我都此類工作作爲我的倉庫:具有非泛型方法約束的泛型類?
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