如何获得表达结果?

时间:2019-03-01 08:33:19

标签: c# expression

我构建如下表达式:

Expression left = Expression.Constant(5, typeof(int));
Expression right = Expression.Constant(6, typeof(int));
Expression result = Expression.Add(left,right);

那么,我可以通过表达式结果获得有关“ 5 + 6”的真实结果吗?

1 个答案:

答案 0 :(得分:2)

我认为您需要将其编译为Func

Expression left = Expression.Constant(5, typeof(int));
Expression right = Expression.Constant(6, typeof(int));
Expression result = Expression.Add(left,right);

var compiled = Expression.Lambda<Func<int>>(result).Compile();
Console.WriteLine(compiled.Invoke());

Expression tree docs

Try it online