views:

278

answers:

2

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

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 the Expression without having to pass the method name as a string (bad for refactoring)?

+3  A: 

You can do it with a helper method:

MethodCallExpression GetCallExpression<T>(Expression<Func<T>> e)
 { return e.Body as MethodCallExpression;
 }

/* ... */
var getRowValExpr = GetCallExpression(x => x.GetRowValue(0));
Mark Cidade
A: 

That's nice. Thanks.

var methodName = ((MethodCallExpression)expr.Body).Method.Name;

gives me the method name, so i don't have to write it as string.

Rauhotz