I would like to generate a Expression that represents this lambda expression:
x => this.SomeMethod(y, x)
I know this is basic, but I'm new to Expressions.
Please notice:
- I want to generate the Expression using Expression static methods like Expression.Call, Expression.Lambda...
- The code is in a Portable Class Library (PCL), if that matters!
Edit
My current code looks like this:
public class Test
{
public static void Main()
{
// as expression tree
var parameter1 = Expression.Parameter(typeof(int), "p1");
var parameter2 = Expression.Parameter(typeof(int), "p2");
var instance = new SampleClass(); // I'm sure I need this, but how to inject it into Expression.Call?
var methodInfo = typeof(SampleClass).GetMethod("SumLargerThan5",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
var lambdaExpression = Expression.Lambda(
Expression.Call(methodInfo, new[] { parameter1, parameter2 }),
parameter1, parameter2);
// testing
var compiledExpr2 = (Action<int, int>)lambdaExpression.Compile();
compiledExpr2(2, 2);
compiledExpr2(4, 2);
}
public class SampleClass
{
private void SampleMethod(int x, int y)
{
Console.WriteLine(this);
}
}
}