解释器模式--Excel公式嵌套

来源:互联网 发布:淘宝朗丝香格里拉窗帘 编辑:程序博客网 时间:2024/05/29 18:39

.e.g. Excel formula =ROUND(SUM($A$1, 2),1)

classBaseExp

{

 publicvirtualobject Evaluate(){ returnnull;}

}

 

classRangeExp:BaseExp

{

    Range _range;

  public RangeExp(Range range)

    {

         _range = range;

     }

  publicoverrideobject Evaluate()

    {

    return _range.Value;

     }

}

 

classConstantExp:BaseExp

{

 Object _constant;

 public ConstantExp(Object constant)

    {

           _constant = constant;

    }

 publicoverrideobject Evaluate()

    {

      return _constant;

     }

}

 

classRoundExp:BaseExp

{

   BaseExp _numberExp;

   BaseExp _digitExp;

   publicRoundExp(BaseExp number, BaseExp digit)

        {

              _numberExp = number;

              _digitExp = digit;

         }

   publicoverrideobject Evaluate()

          {

       returnMath.Round(_numberExp.Evaluate(), _digitExp.Evaluate());

          }

}

classSumExp:BaseExp

{

    List<BaseExp> _params = newList<BaseExp>();

    public SumExp(param BaseExp[] args)

           {

        foreach(BaseExp exp in args)

                    {

                        _params.Add(exp);

                      }

            }

    public SumExp(Range range)

          {

         //loop for each single cell in range

      foreach(Range cell in totalCellList)

               {

            _params.Add(new RangeExp(cell));

                }

          }

    publicoverrideobject Evaluate()

         {

        double total = 0;

       foreach(BaseExp exp in _params)

               {

            total += (double)exp.Evaluate();

               }

       return total;

       }

}

适合有多种解析方式且任意一个解释方式又可以被其他解析方式引用。

0 0
原创粉丝点击