5

式ツリー内でインスタンス メソッドを呼び出す最良の方法は何ですか? 私の現在の解決策は、インターフェイス IColumn のインターフェイス メソッド「オブジェクト 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);            
        }

もっと速い方法はありますか?メソッド名を文字列として渡さずに Expression を作成することは可能ですか (リファクタリングには適していません)?

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 に答える