예제 #1
0
        public Func <int, int> Factorial()
        {
            // Creating a parameter expression.
            var value = Expression.Parameter(typeof(int), "value");

            // Creating an expression to hold a local variable.
            var result = Expression.Variable(typeof(int), "result");

            // Creating a label to jump to from a loop.
            var label = Expression.Label(typeof(int));

            // Creating a method body.
            var block = Expression.Block(
                new[] { result },
                Expression.Assign(result, Expression.Constant(1)),
                Expression.Loop(
                    Expression.IfThenElse(
                        Expression.GreaterThan(value, Expression.Constant(1)),
                        Expression.MultiplyAssign(result,
                                                  Expression.PostDecrementAssign(value)),
                        Expression.Break(label, result)
                        ),
                    label
                    )
                );

            return(Expression.Lambda <Func <int, int> >(block, value).Compile());
        }