Давайте извлекаем модель в виде словаря для всех этих операторов:
private static Dictionary<string, Func<double, double, double>> s_Operators = new
Dictionary<string, Func<double, double, double>>() {
{ "+", (x, y) => x + y },
{ "-", (x, y) => x - y },
{ "*", (x, y) => x * y },
{ "/", (x, y) => x / y },
//TODO: Add new operations if you want, e.g.
// { "^", (x, y) => Math.Pow(x, y) },
};
Тогда вы можете легко реализовать Calculate
:
public static double Calculate(double firstNumber, double secondNumber, string operation)
{
return s_Operators.TryGetValue(operation, out var func)
? func(firstNumber, secondNumber)
: throw new ArgumentException($"Unknown {operation} operation", nameof(operation));
}
Обратите внимание, что вам нужно Dispose
DataTable
, поэтому вычисления с помощью DataTable
будут выглядеть примерно так:
private static double TableCompute(string formula) {
using (DataTable table = new DataTable()) {
return Convert.ToDouble(table.Compute(formula, null));
}
}