委托
//创建一个委托
public delegate decimal MathOperation(decimal left, decimal right);
//创建方法参数和返回结果符合委托的定义
public static decimal Add(decimal left, decimal right)
{
return left + right;
}
public static decimal Subtract(decimal left, decimal right)
{
return left - right;
}
public static decimal Multiply(decimal left, decimal right)
{
return left * right;
}
public static decimal Divide(decimal left, decimal right)
{
return left / right;
}
//返回委托类型
private static MathOperation GetOperation(char oper)
{
switch(oper)
{
case '+': return Add;
case '-': return Subtract;
case '*': return Multiply;
case '/': return Divide;
}
throw new NotSupportedException("");
}
//封装一个方法用来把操作数和符号考虑进来,返回委托类型
private static decimal Eval(string expr)
{
var elements = expr.Split(new []{' '}, 3);
var left = Decimal.Parse(elements[0]);
var right = Decimal.Parse(elements[1]);
var ope = elements[2][0];
return GetOperation(op)(left, right);
}
void Main()
{
Console.WriteLine(Eval("1 3 +"));
}