5

在表达式树中调用实例方法的最佳方式是什么?对于接口 IColumn 的接口方法“object GetRowValue(rowIndex)”,我当前的解决方案是这样的。

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);            
        }

有更快的方法吗?是否可以创建表达式而不必将方法名称作为字符串传递(不利于重构)?

4

1 回答 1

8

您可以使用辅助方法来做到这一点:

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

/* ... */
var getRowValExpr = GetCallExpression(x => x.GetRowValue(0));
于 2008-12-27T11:32:03.553 回答