public int Calculate(string expression) { Context context = new Context(); IList<IExpression> tree = new List<IExpression>(); //词法和语法分析 char[] elements = expression.ToCharArray(); foreach(char c in elements) { if ((c == '+') || (c == '-')) tree.Add(new Operator(c)); else tree.Add(new Operand((int)(c-48))); } //便利中间每个过程 foreach(IExpression exp in tree) exp.Evaluate(context); return context.Value; }
public virtual void Evaluate(Context context) { context.Operator = op; }
//根据操作符执行计算 public virtual void Evaluate(Context c) { switch(c.Operator) { case '\0': c.Value = num; break; case '+': c.Value += num; break; case '-': c.Value -= num; break; } }