Обобщить метод - C#
Формулировка задачи:
Есть некий класс, который отвечает за работу с БД. В нём довольно прилично методов, которые просто вызывают сохраненную процедуру с параметрами. В общем случае всё выглядит так.
То есть, методы по сути отличаются только передаваемыми параметрами и возвращаемым значение, а также во всех присутствует логирование, открытие/закрытие соединения. В принципе не смертельно, но замечаю что сильно много копи-пастю.
public object Method(type1 value1, type2 value2...) //public void Method(type1 value1, type2 value2...) { this.sqlCommand.CommandText = "STORE_PROCEDURE"; this.sqlCommand.Parameters.Clear(); this.sqlCommand.Parameters.AddWithValue("VALUE_1", value1); this.sqlCommand.Parameters.AddWithValue("VALUE_2", value2); try { this.log.Debug("open connection"); this.sqlConnection.Open(); this.log.Debug("execute store procedure STORE_PROCEDURE"); var result = this.sqlCommand.ExecuteScalar(); return result; } catch (Exception ex) { this.log.Error(ex); throw ex; } finally { this.log.Debug("close connection"); this.sqlConnection.Close(); } }
Решение задачи: «Обобщить метод»
textual
Листинг программы
class Program { static void Main(string[] args) { IOperation firstOperation = new AddOperation(4,5); IOperation secondOperation = new SubOperation(4, 5); IOperation thirdOperation = new MultOperation(4, 5); DoWork(firstOperation); DoWork(secondOperation); DoWork(thirdOperation); } static void DoWork(IOperation operation) { operation.DoOperation(); } } interface IOperation { int FirstValue { get; set; } int SecondValue { get; set; } void DoOperation(); } class AddOperation : IOperation { public int FirstValue { get; set; } public int SecondValue { get; set; } public void DoOperation() { Console.WriteLine(operation.FirstValue+operation.SecondValue); } public AddOperation(int first, int second) { FirstValue = first; SecondValue = second; } } class SubOperation : IOperation { public int FirstValue { get; set; } public int SecondValue { get; set; } public void DoOperation() { Console.WriteLine(operation.FirstValue-operation.SecondValue); } public SubOperation(int first, int second) { FirstValue = first; SecondValue = second; } } class MultOperation : IOperation { public int FirstValue { get; set; } public int SecondValue { get; set; } public void DoOperation() { Console.WriteLine(operation.FirstValue*operation.SecondValue); } public MultOperation(int first, int second) { FirstValue = first; SecondValue = second; } }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д