多くの非常に類似したオブジェクトの初期化を一般化する次のコードがあります。C# コードを一般化しました (以下を参照)。誰もがより良い方法を知っていますか? これはそれほど悪くはありませんが、それでもコピー/貼り付けが必要であり、これは避けたいと思います。
private Tuple<SqlCommand, SqlCommand, SqlCommand, SqlCommand, SqlDataAdapter> initializeCommandsFor (string type) {
SqlCommand selectCommand;
SqlCommand insertCommand;
SqlCommand updateCommand;
SqlCommand deleteCommand;
SqlDataAdapter dataAdapter;
selectCommand = new SqlCommand("Get" + type + "Data", cntn);
selectCommand.CommandType = CommandType.StoredProcedure;
insertCommand = new SqlCommand("Insert" + type, cntn);
insertCommand.CommandType = CommandType.StoredProcedure;
updateCommand = new SqlCommand("Update" + type, cntn);
updateCommand.CommandType = CommandType.StoredProcedure;
deleteCommand = new SqlCommand("Delete" + type, cntn);
deleteCommand.CommandType = CommandType.StoredProcedure;
cntn.Open();
SqlCommandBuilder.DeriveParameters(selectCommand);
cntn.Close();
dataAdapter = new SqlDataAdapter(selectCommand);
dataAdapter.InsertCommand = insertCommand;
dataAdapter.UpdateCommand = updateCommand;
dataAdapter.DeleteCommand = deleteCommand;
return Tuple.Create(selectCommand, insertCommand, updateCommand, deleteCommand, dataAdapter);
}
private void customerCommands () {
var commands = initializeCommandsFor("Customer");
customerSelectCommand = commands.Item1;
customerInsertCommand = commands.Item2;
customerUpdateCommand = commands.Item3;
customerDeleteCommand = commands.Item4;
customerDataAdapter = commands.Item5;
}
private void competitorCommands () {
var commands = initializeCommandsFor("Competitor");
competitorSelectCommand = commands.Item1;
competitorInsertCommand = commands.Item2;
competitorUpdateCommand = commands.Item3;
competitorDeleteCommand = commands.Item4;
competitorDataAdapter = commands.Item5;
}