Rau*_*otz 4 c# linq expression-trees
在表达式树中调用实例方法的最佳方法是什么?我目前的解决方案是接口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);
}
Run Code Online (Sandbox Code Playgroud)
有更快的方法吗?是否可以创建表达式而无需将方法名称作为字符串传递(对于重构不好)?
您可以使用辅助方法执行此操作:
MethodCallExpression GetCallExpression<T>(Expression<Func<T>> e)
{
return e.Body as MethodCallExpression;
}
/* ... */
var getRowValExpr = GetCallExpression(x => x.GetRowValue(0));
Run Code Online (Sandbox Code Playgroud)