Best way to call instance method in expression trees?

What is the best way to invoke an instance method in an Expression Tree? My current solution is something like this for the interface method "GetRowValue object (rowIndex)" of the IColumn interface.

public static Expression CreateGetRowValueExpression( IColumn column, ParameterExpression rowIndex) { MethodInfo methodInfo = column.GetType().GetMethod( "GetRowValue", BindingFlags.Instance | BindingFlags.Public, null, CallingConventions.Any, new[] { typeof(int) }, null); var instance = Expression.Constant(column); return Expression.Call(instance, methodInfo, rowIndex); } 

Is there a faster way? Is it possible to create an expression without having to pass the method name as a string (bad for refactoring)?

+4
source share
1 answer

You can do this with a helper method:

 MethodCallExpression GetCallExpression<T>(Expression<Func<T>> e) { return e.Body as MethodCallExpression; } /* ... */ var getRowValExpr = GetCallExpression(x => x.GetRowValue(0)); 
+8
source

All Articles