如何创建循环表达式树

时间:2019-03-15 13:13:37

标签: c# loops .net-core expression-trees

我正在尝试创建一个将生成此方法的表达式树:

LabelTarget

我不了解type的工作方式。在我的情况下,我想跳到……没有任何价值。我不明白为什么它确实需要public static Func<int,int> MakeExpression() { //input ParameterExpression parameter = Expression.Parameter(typeof(int)); //define local variables and initialize them Expression cntVarExpr = Expression.Variable(typeof(int),"cnt"); Expression sumVarExpr = Expression.Variable(typeof(int), "sum"); Expression initCntExpr = Expression.Assign(cntVarExpr, Expression.Constant(0)); Expression initSumExpr = Expression.Assign(sumVarExpr, Expression.Constant(0)); //loop condition Expression condExpr = Expression.GreaterThanOrEqual(cntVarExpr, parameter); //block if true MethodInfo method = typeof(Console).GetMethod("WriteLine",new Type[] { typeof(int)}); Expression printExpr = Expression.Call(null, method,cntVarExpr); //static method LabelTarget label = Expression.Label(typeof(int)); //am not sure about this one ? what Expression bkExpr = Expression.Break(label, sumVarExpr); BlockExpression block = Expression.Block(printExpr, bkExpr); //loop body Expression ifExpr = Expression.IfThen(condExpr, block); Expression addExpr = Expression.AddAssign(sumVarExpr,cntVarExpr); Expression incrExpr = Expression.Add(cntVarExpr, Expression.Constant(1)); BlockExpression loopBodyExpr = Expression.Block(ifExpr, addExpr,incrExpr); LoopExpression loopExpr = Expression.Loop(loopBodyExpr); //method body Expression returnExpr = Expression.Return(label, sumVarExpr,typeof(int)); //final expression BlockExpression bigExpression = Expression.Block(initCntExpr, initSumExpr, loopExpr, returnExpr); var meth = Expression.Lambda<Func<int, int>>(bigExpression,parameter).Compile(); return meth; }

到目前为止,这是我的代码:

'variable 'cnt' of type 'System.Int32' referenced from scope '', but it is not defined'

我不断收到此错误:

import axios from 'axios'
// ...
axios.defaults.headers.common.Authorization = token;

1 个答案:

答案 0 :(得分:0)

在块中使用VariableExpression时,必须将该变量传递到variables的{​​{1}}参数中。这就是导致您出错的原因。

恐怕我没有时间详细研究您的代码,但是我使用表达式重写了您的C#:

Expression.Block