Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

reflection - How do I compile an Expression Tree into a callable method, C#?

I have an expression tree I have created by parsing an Xml using the expression class in C#. See this question.

I only have Add, Subtract, Divide, Multiply, Parameters, And and Or in my Expression Tree. Is there a way to convert this ExpressionTree into a callable method? ...or do I have to emit the IL manually?

Kind regards,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to create a lambda - i.e.

var lambda = Expression.Lambda<Func<float,int>>(body, param);
Func<float,int> method = lambda.Compile();
int v = method(1.0); // test

where "body" is your expression tree (taking a float, returning an int) involving the ParameterExpression param.

You might also find this and this helpful.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...