【问题标题】:Expression.Call with generic typesExpression.Call 使用泛型类型
【发布时间】:2016-03-13 00:19:25
【问题描述】:

类测试器正在尝试对通用可查询对象调用 sum。它在 MethodCallExpression 上中断。所以我不确定下面的行是否真的会运行。

我也尝试过在单独的调用中获取 MethodInfo,但它总是返回 null。所以我相信用我提供的参数找到“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);

        }
    }

【问题讨论】:

    标签: c# entity-framework generics lambda expression


    【解决方案1】:

    你试过了吗?

    var sum = new Func<IQueryable<TSource>, Expression<Func<TSource, int>>, int>(Queryable.Sum).Method;
    

    【讨论】:

    • 谢谢。再加上一点小改动,MethodCallExpression expr = Expression.Call(sum, source.Expression, lambdaa); object result = Expression.Lambda(expr).Compile().DynamicInvoke(); 我就可以打电话了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多