开发者

What expression method to use to get back parameter?

开发者 https://www.devze.com 2023-03-10 10:23 出处:网络
Simple question.I am trying to create a basic lambda expression that returns the parameter. (i, o) => o

Simple question. I am trying to create a basic lambda expression that returns the parameter.

(i, o) => o

I have the first part:

ParameterExpression p1 = Ex开发者_Go百科pression.Parameter(relationshipItems.ElementType, "i");
ParameterExpression p2 = Expression.Parameter(instanceEntities.ElementType, "o");

And the last part:

LambdaExpression lambda = Expression.Lambda(p2return, p1, p2);

What method do I use to get back the parameter, presumably as a UnaryExpression(p2return)?


Just set the body to be the second parameter, p2. You already have the reference.

var p1 = Expression.Parameter(relationshipItems.ElementType, "i");
var p2 = Expression.Parameter(instanceEntities.ElementType, "o");
var body = p2;
var lambda = Expression.Lambda(body, p1, p2);


If, for the sake of example, we assume p1 is an int and p2 is a string then this:

var p1=Expression.Parameter(typeof(int),"i");
var p2=Expression.Parameter(typeof(string),"o");

var lambda=Expression.Lambda(p2,p1,p2);
var function=lambda.Compile() as Func<int,string,string>;
var result=function(10,"hello");

will generate a function that returns "o". The lambda will return the value in the last expression in its body, which in the above example is just the parameter p2.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号