ExpressionTreeの練習にC#3.0で簡易電卓(?)作ってみたよ!

using CalcFunc = Func<int, int, int>;

public class Calc
{
	private Expression<CalcFunc> baseExp = ( ( a, b ) => a + b );
	private delegate BinaryExpression Operator( Expression a, Expression b );
	private static Dictionary<string, Operator> table = new Dictionary<string,Operator>();
	static Calc()
	{
		Operator o = Expression.Add;
		table.Add( "たす", Expression.Add );
		table.Add( "ひく", Expression.Subtract );
		table.Add( "わる", Expression.Divide );
		table.Add( "かける", Expression.Multiply );
		table.Add( "あまり", Expression.Modulo );
	}
	private int Calculate( Operator @operator, int a, int b )
	{
		BinaryExpression tree = this.baseExp.Body as BinaryExpression;
		Expression<CalcFunc> newExp = Expression.Lambda<CalcFunc>(
			@operator( tree.Left, tree.Right ), this.baseExp.Parameters.ToArray() );
		CalcFunc func = newExp.Compile();
		return func( a, b );
	}
	public void Run( int a, string @operator, int b)
	{
		int result = this.Calculate( table[ @operator ], a, b );
		Console.WriteLine( "{0}です。", result );
	}
	public void Test()
	{
		Run( 98, "たす", 2 );
		Run( 16, "かける", 16 );
		Run( 100, "わる", 100 );
		Run( 0, "ひく", 1 );
		Run( 3, "あまり", 2 );
	}
}