2011-12-20 145 views
0

我有一個使用泛型和反射的數據映射助手類。因爲我在我的幫助程序類中使用了反射和泛型,所以標準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); 
    } 
+1

啊,[CRTP](http://blogs.msdn.com/b/ericlippert/archive/2011/02/03/curiouser-and-curiouser.aspx) – SLaks

回答

2

只投thisT

dataUtils.CreateParams((T)this, true); 

如果您創建public class Evil : BusinessObject<Good>,則會引發InvalidCastException。

+0

謝謝 - 我試過了,那拋出:無法將類型'Entities.BusinessObject '轉換爲'T' – Ripside

+0

這是一個_compile-time_錯誤;它不會拋出。將',class'添加到通用約束中。 – SLaks

+0

當然。雖然這並沒有幫助。 '公共抽象類BusinessObject 其中T:class,new()'。爲了澄清並從等式中刪除我的外部幫助,我將使用它來進行測試(同樣的錯誤):'T myEntity =(T)this;' – Ripside

相關問題