-
Notifications
You must be signed in to change notification settings - Fork 5.1k
/
Copy pathExpressionTreeBuildingSampleTwo.cs
64 lines (52 loc) · 1.91 KB
/
ExpressionTreeBuildingSampleTwo.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System.Linq.Expressions;
using ExpressionVisitor;
namespace ExpressionTreeSamples;
public class ExpressionTreeBuildingSampleTwo : Sample
{
public override string Name { get; } = "Building Expression Trees, Sample 2: Building Loops and Conditionals";
public override void Run()
{
// This code builds the equivalent of:
Func<int, int> factorialFunc = (n) =>
{
var res = 1;
while (n > 1)
{
res = res * n;
n--;
}
return res;
};
var nArgument = Expression.Parameter(typeof(int), "n");
var result = Expression.Variable(typeof(int), "result");
// Creating a label that represents the return value
LabelTarget label = Expression.Label(typeof(int));
var initializeResult = Expression.Assign(result, Expression.Constant(1));
// This is the inner block that performs the multiplication,
// and decrements the value of 'n'
var block = Expression.Block(
Expression.Assign(result,
Expression.Multiply(result, nArgument)),
Expression.PostDecrementAssign(nArgument)
);
// Creating a method body.
BlockExpression body = Expression.Block(
new[] { result },
initializeResult,
Expression.Loop(
Expression.IfThenElse(
Expression.GreaterThan(nArgument, Expression.Constant(1)),
block,
Expression.Break(label, result)
),
label
)
);
var factorial = Expression.Lambda(body, nArgument);
// Compile and run an expression tree.
var func = (Func<int, int>)factorial.Compile();
Console.WriteLine(func(5));
var visitor = Visitor.CreateFromExpression(factorial);
visitor.Visit("");
}
}