代码之家  ›  专栏  ›  技术社区  ›  Rauhotz

在表达式树中调用实例方法的最佳方法?

  •  4
  • Rauhotz  · 技术社区  · 16 年前

    在表达式树中调用实例方法的最佳方法是什么?对于接口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);            
            }
    

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

    1 回复  |  直到 12 年前
        1
  •  8
  •   TheCloudlessSky    12 年前

    您可以使用helper方法:

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