コンソールアプリケーションで実行されるいくつかのコードをリファクタリングしたいと思います。 Appは外部データベースを更新し、MySQLまたはSQL Serverのいずれかをサポートするように最近更新されました。そこで、MySqlConnectionとMySqlCommand(など)を使用するメソッドシグネチャと、SqlConnectionとSqlCommand(など)を使用するメソッドシグネチャがあるため、多数の重複したコードを持つほぼ同じメソッドが2つあります。異なる入力オブジェクトでジェネリック関数を使用するためのリファクタリング
コードは、ADOオブジェクトの明白な違いを除いて、本質的に同一です。
私がしたいことは次のようなものです。私はここでいくつかの投稿を見てきました(例えばHow do I use reflection to call a generic method?のような)と、動的なタイプでこれを設定する方法を示す他のサイトは素晴らしいですが、例のどれもfoo.GetType )を使用して、動的型が正しいことを証明します。
したがって、どのようにそのダイナミックタイプのメソッドを呼び出しますか?もちろん、これを設定しようとすると、sqlConnectionパラメータでOpen()メソッドを呼び出そうとするとコンパイルされません。
ここで私が達成しようとしているものの一種です:事前に
private static void TransferXmlData(ExportManifest m_settings, XmlNodeList xmlNodeList)
{
if (m_Settings.ServerType.ToLower() == "mysql")
{
using (MySqlConnection mySqlConnection = new MySqlConnection(m_Settings.TargetData.ConnectionString))
{
MySqlCommand mySqlCommand =
new MySqlCommand(Program.GetCommandTextTemplate(m_settings), mySqlConnection);
PrepareSqlCommand(mySqlConnection, mySqlCommand, m_settings)
}
}
else
{
using (SqlConnection sqlConnection =
new SqlConnection(m_Settings.TargetData.ConnectionString))
{
SqlCommand sqlCommand =
new SqlCommand(Program.GetCommandTextTemplate(m_settings), sqlConnection);
PrepareSqlCommand(sqlConnection, sqlCommand, m_settings)
}
}
}
private static void PrepareSqlCommand<T>(T sqlConnection, T sqlCommand, ExportManifest m_settings)
{
// Potentially a lot of code here that looks just like the
// code in the else block, Except that it uses the
// MySqlConnection objects instead of SqlConnection
// Do some stuff
sqlConnection.Open(); // obviously doesn't work
}
ありがとう!
'IDbConnection'と' IDbCommand'を期待してメソッドを作ることはできませんか? – Sehnsucht