我有一個使用泛型和反射的數據映射助手類。因爲我在我的幫助程序類中使用了反射和泛型,所以標準CRUD操作的代碼在所有業務對象中都是相同的(如在基類Create()方法中所見),所以我試圖使用基本的BusinessObject類來處理重複的方法。引用基類中的派生對象
我希望基類能夠調用我的通用DataUtils方法,例如接受對派生的業務對象對象的引用來填充SQL參數。
DataUtils.CreateParams需要T和bool對象(表示插入或更新)。
我想通過「this」代表我的派生對象的基類,但我得到編譯錯誤「最好的重載比賽包含無效的參數。」
如果我在派生類中實現了Create(),並且傳遞了基類的Create方法對「this」的引用,它就起作用了 - 但接下來我仍然在每個業務對象中同樣實現所有CRUD方法類。我希望基類來處理這些。
基類可能調用方法並將引用傳遞給派生對象嗎?
這裏是我的基類:
public abstract class BusinessObject<T> where T:new()
{
public BusinessObject()
{ }
public Int64 Create()
{
DataUtils<T> dataUtils = new DataUtils<T>();
string insertSql = dataUtils.GenerateInsertStatement();
using (SqlConnection conn = dataUtils.SqlConnection)
using (SqlCommand command = new SqlCommand(insertSql, conn))
{
conn.Open();
//this line is the problem
command.Parameters.AddRange(dataUtils.CreateParams(obj, true));
return (Int64)command.ExecuteScalar();
}
}
}
}
而派生類:
public class Activity: BusinessObject<Activity>
{
[DataFieldAttribute(IsIndentity=true, SqlDataType = SqlDbType.BigInt)]
public Int64 ActivityId{ get; set; }
///...other mapped fields removed for brevity
public Activity()
{
ActivityId=0;
}
//I don't want to have to do this...
public Int64 Create()
{
return base.Create(this);
}
啊,[CRTP](http://blogs.msdn.com/b/ericlippert/archive/2011/02/03/curiouser-and-curiouser.aspx) – SLaks