[ 来源:http://www.it55.com | 作者: | 时间:2007-12-30 | 收藏 | 推荐 ] 【大 中 小】
break;
ExpressionToken token = exp[index];
switch (token.Type)
{
//如果是数字,则将值存入 digit 中
case TokenType.Numeric:
digit.Add(Convert.ToDecimal(exp[index].Data));
index++;
break;
case TokenType.Operator:
//二元表达式,需要二个参数, 如果是函数的话,可能需要更多的参数
int paramCount = 2;
//计算操作数的值
if (digit.Count < paramCount)
{
throw new ExpressionException("缺少操作数");
}
//传入参数
decimal?[] data = new decimal?[paramCount];
for (int i = 0; i < paramCount; i++)
{
data[i] = digit[index - paramCount + i];
}
//将计算结果再存入当前节点
exp[index].Data = CalcOperator((OperatorType)token.Data, data);
exp[index].Type = TokenType.Numeric;
//将操作数节点删除
for (int i = 0; i < paramCount; i++)
{
exp.RemoveAt(index - i - 1);
digit.RemoveAt(index - i - 1);
}
index -= paramCount;
break;
default:
break;
}
}
if (exp.Count == 1)
{
switch (exp[0].Type)
{
case TokenType.Numeric:
return exp[0].Data;
default:
throw new ExpressionException("缺少操作数", 1002);
}
}
else
{
throw new ExpressionException("缺少操作符或操作数", 1002);
}
}
public object Calc()
{
return CalcInner(lstExp);
}
/**//// <summary>
/// 计算表达式的值
/// (因为不确定参数有几个,所以用数组传进来)
/// 比如,函数可能只需要1个参数,也可能需要3个参数
/// </summary>
public object CalcOperator(OperatorType op, decimal?[] data)
{
//暂只编号写基本四则运算的代码,无函数计算
decimal? d1 = data[0];
decimal? d2 = data[1];
if (d1 == null || d2 == null)
return DBNull.Value;
switch (op)
{
case OperatorType.Plus:
return d1 + d2;
case OperatorType.Subtract:
return d1 - d2;
case OperatorType.MultiPly:
return d1 * d2;
case OperatorType.Divide:
if (d2 == 0)
throw new DivideByZeroException();
return d1 / d2;
}
return 0;
}
}
里面的一些基本函数不作赘述。
该函数使用很简单,只有个Calc方法
Expression exp = new Expression("12+36*9");
object result = exp.Calc()); //当然,现在还没转换后缀表达式功能,所以无法计算 :)
...........待续
(编辑:IT资讯之家 www.it55.com)