在基类中引用派生对象



我有一个使用泛型和反射的数据映射助手类。

由于我在助手类中使用反射和泛型,因此标准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);
    }

this转换为T:

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

如果你创建了一个public class Evil : BusinessObject<Good>,那将抛出一个InvalidCastException

最新更新