Expressions ... What am I doing wrong?

I decided to take some golden time to learn a little about expressions. I try a very simple exercise, namely adding two numbers. I got into an exception that turned out to be difficult to find.

Here is my code

Expression<Func<int,int,int>> addExpr = (x, y) => x + y; var p1 = Expression.Parameter(typeof(int), "p1"); var p2 = Expression.Parameter(typeof(int), "p2"); var lambda = Expression.Lambda<Func<int,int,int>>(addExpr, p1, p2); //<-here var del = lambda.Compile(); var result = del(2,3); //expect 5 

but this throws an ArgumentException: an expression like 'System.Func`3 [System.Int32, System.Int32, System.Int32] cannot be used for the return type' System.Int32 '

in the line above. What I did wrong?

+4
source share
3 answers

You need to wrap addExpr in the call using expression parameters

 Expression<Func<int,int,int>> addExpr = (x, y) => x + y; var p1 = Expression.Parameter(typeof(int), "p1"); var p2 = Expression.Parameter(typeof(int), "p2"); var invokeExpression=Expression.Invoke(addExpr,p1,p2); var lambda = Expression.Lambda<Func<int,int,int>>(invokeExpression,p1,p2); var del = lambda.Compile(); var result=del(2,3); 

It is called how you enter p1 in x and p2 in y, otherwise you could just write above, like

 var p1 = Expression.Parameter(typeof(int), "p1"); var p2 = Expression.Parameter(typeof(int), "p2"); var lambda=Expresion.Lambda<Func<int,int,int>>(Expression.Add(p1,p2),p1,p2); var del = lambda.Compile(); var result=del(2,3); 

Otherwise, you need to capture the body of the expression in lambda and pass the parameters of the expression.

 var lambda=Expresion.Lambda<Func<int,int,int>>(addExpr.Body,addExpr.Parameters); 
+4
source

Your code should be:

 var lambda = Expression.Lambda<Func<Expression<Func<int, int, int>>, int, int>(addExpr, p1, p2); 

Your current code expects an int and your transition to Expression<Func<int, int, int>> .

Update

Actually the above will not compile, you will need to do:

 var lambda = Expression.Lambda<Func<int, int, int>>(Expression.Add(p1, p2), p1, p2); 
+2
source

You need to decompose the body of addExpr or just just write it from scratch, i.e. Expression.Add(p1,p2) instead of addExpr .

+1
source

Source: https://habr.com/ru/post/1432473/


All Articles