Expression.Call 具有通用类型
Expression.Call with generic types
class 测试人员正在尝试对通用可查询对象调用 sum。它在 MethodCallExpression 上中断。所以我不确定下面的行是否真的 运行 。
我也尝试过在单独的调用中获取 MethodInfo,但它始终 returns 为空。所以我相信用我提供的参数找到 "Sum" 函数是个麻烦。任何帮助是极大的赞赏。
class test
{
public int sumMe { get; set; }
}
[TestMethod]
public void foo()
{
var list = new List<test>();
list.Add(new test() { sumMe = 1 });
list.Add(new test() { sumMe = 2 });
list.Add(new test() { sumMe = 3 });
tester.run(list.AsQueryable(), "sumMe");
}
class tester
{
public static void run<TSource>(IQueryable<TSource> source, string field)
{
ParameterExpression instance = Expression.Parameter(typeof(TSource), "x");
MemberExpression propertyOnInstance = Expression.PropertyOrField(instance, field);
Type typeOfGenericFunction = typeof(Func<,>).MakeGenericType(typeof(TSource), typeof(int));
LambdaExpression lambda = Expression.Lambda(typeOfGenericFunction, propertyOnInstance, instance);
MethodCallExpression expr = Expression.Call(typeof(Queryable), "Sum", new Type[] { typeof(TSource) }, propertyOnInstance, lambda);
var hopingThisWorks = source.Provider.CreateQuery<TSource>(expr);
}
}
你试过了吗?
var sum = new Func<IQueryable<TSource>, Expression<Func<TSource, int>>, int>(Queryable.Sum).Method;
class 测试人员正在尝试对通用可查询对象调用 sum。它在 MethodCallExpression 上中断。所以我不确定下面的行是否真的 运行 。
我也尝试过在单独的调用中获取 MethodInfo,但它始终 returns 为空。所以我相信用我提供的参数找到 "Sum" 函数是个麻烦。任何帮助是极大的赞赏。
class test
{
public int sumMe { get; set; }
}
[TestMethod]
public void foo()
{
var list = new List<test>();
list.Add(new test() { sumMe = 1 });
list.Add(new test() { sumMe = 2 });
list.Add(new test() { sumMe = 3 });
tester.run(list.AsQueryable(), "sumMe");
}
class tester
{
public static void run<TSource>(IQueryable<TSource> source, string field)
{
ParameterExpression instance = Expression.Parameter(typeof(TSource), "x");
MemberExpression propertyOnInstance = Expression.PropertyOrField(instance, field);
Type typeOfGenericFunction = typeof(Func<,>).MakeGenericType(typeof(TSource), typeof(int));
LambdaExpression lambda = Expression.Lambda(typeOfGenericFunction, propertyOnInstance, instance);
MethodCallExpression expr = Expression.Call(typeof(Queryable), "Sum", new Type[] { typeof(TSource) }, propertyOnInstance, lambda);
var hopingThisWorks = source.Provider.CreateQuery<TSource>(expr);
}
}
你试过了吗?
var sum = new Func<IQueryable<TSource>, Expression<Func<TSource, int>>, int>(Queryable.Sum).Method;