私はジェネリックとリフレクションを使用するデータマッピングヘルパークラスを持っています。基本クラスの派生オブジェクトの参照
私はヘルパークラスでリフレクションとジェネリックを使用しているので、標準のCRUD操作のコードはすべてのビジネスオブジェクト(基本クラスのCreate()メソッド)に見られるように同じです。基本のBusinessObjectクラスを使用して反復メソッドを処理します。
たとえば、SQLパラメータを設定するために派生ビジネスオブジェクトオブジェクトへの参照を受け入れる、汎用クラスのDataUtilsメソッドを呼び出せるようにしたいとします。
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();
}
}
}
}
と派生クラス:ちょうどT
にthis
をキャスト
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