Ejemplo n.º 1
0
        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;
        }
Ejemplo n.º 2
0
 public virtual void Evaluate(Context context)
 {
     context.Operator = op;
 }
Ejemplo n.º 3
0
 //根据操作符执行计算
 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;
     }
 }