using DynamicExpresso; using DynamicExpresso.Exceptions; using System.Collections.Generic; using System.Linq; namespace IStation.DynamicExpresso { /// /// 计算器 /// public class Calculator { /// /// 计算 /// /// 计算表达式 /// 变量与值对应字典 /// public static double Eval(string expression, Dictionary dict) { Interpreter interpreter = new Interpreter(); if (dict != null && dict.Count > 0) { foreach (var item in dict) { if (!string.IsNullOrEmpty(item.Key)) { interpreter.SetVariable(item.Key, item.Value); } } } return interpreter.Eval(expression); } /// /// 计算 /// /// 计算表达式 /// 变量 /// 值 /// public static double Eval(string expression, string arg, double value) { Interpreter interpreter = new Interpreter(); if (!string.IsNullOrEmpty(arg)) { interpreter.SetVariable(arg, value); } return interpreter.Eval(expression); } /// /// 计算(包含【0,1】个变量) /// /// 计算表达式 /// 参数 /// public static double Eval(string expression, double value) { Interpreter interpreter = new Interpreter(); var args = interpreter.DetectIdentifiers(expression).UnknownIdentifiers; if (args.Count() > 1) { throw new UnknownIdentifierException(args.Last(), args.Count() - 1); } if (args.Count() == 1) { interpreter.SetVariable(args.First(), value); } return interpreter.Eval(expression); } } }