【问题标题】:Calling a Method from an Expression从表达式调用方法
【发布时间】:2009-01-13 14:45:00
【问题描述】:

使用 Expression.Call 时方法“Any”采用什么类型和参数?

我有一个内部表达式和一个外部表达式,我想与 Any 一起使用。表达式是以编程方式构建的。

内部(有效):

ParameterExpression tankParameter = Expression.Parameter(typeof(Tank), "t");
Expression tankExpression = Expression.Equal(
    Expression.Property(tankParameter, "Gun"),
    Expression.Constant("Really Big"));

Expression<Func<Tank, bool>> tankFunction = 
    Expression.Lambda<Func<Tank, bool>>(tankExpression, tankParameter); 

外部(看起来正确):

ParameterExpression vehicleParameter = Expression.Parameter(typeof(Vehicle), "v");

Expression vehicleExpression = Expression.Lambda(
    Expression.Property(
        vehicleParameter, 
        typeof(Vehicle).GetProperty("Tank")), 
    vehicleParameter);

这给了我两种表达方式:

v => v.Tank
t => t.Gun == "Really Big";

而我正在寻找的是:

v => v.Tank.Any(t => t.Gun == "Really Big");

我正在尝试使用 Expression.Call 方法来使用“Any”。 1. 这是正确的做法吗? 2.以下抛出异常, “'System.Linq.Queryable' 类型上没有方法 'Any' 与提供的参数兼容。”

我是这样称呼 Any 的:

Expression any = Expression.Call(
    typeof(Queryable),
    "Any",
    new Type[] { tankFunction.Body.Type }, // this should match the delegate...
    tankFunction);

Any 调用是如何从 vehicleExpression 链接到 tankFunction 的?

【问题讨论】:

    标签: c# lambda


    【解决方案1】:

    我在尝试让string.Contains 工作时遇到了类似的问题;我只是改用GetMethod/MethodInfo 方法;但是 - 它很复杂,因为它是一种通用方法...

    这应该是正确的MethodInfo - 但如果没有更清楚地了解TankVehicle,就很难给出完整的(可运行的)答案:

       MethodInfo method = typeof(Queryable).GetMethods()
            .Where(m => m.Name == "Any"
                && m.GetParameters().Length == 2)
            .Single().MakeGenericMethod(typeof(Tank));
    

    请注意,扩展方法向后工作 - 所以您实际上想使用两个参数(源和谓词)调用 method

    类似:

       MethodInfo method = typeof(Queryable).GetMethods()
            .Where(m => m.Name == "Any" && m.GetParameters().Length == 2)
            .Single().MakeGenericMethod(typeof(Tank));
    
        ParameterExpression vehicleParameter = Expression.Parameter(
            typeof(Vehicle), "v");
        var vehicleFunc = Expression.Lambda<Func<Vehicle, bool>>(
            Expression.Call(
                method,
                Expression.Property(
                    vehicleParameter,
                    typeof(Vehicle).GetProperty("Tank")),
                tankFunction), vehicleParameter);
    

    如果有疑问,请使用反射器(并稍微摆弄一下;-p)-例如,我根据您的规范编写了一个测试方法:

    Expression<Func<Vehicle, bool>> func = v => v.Tank.Any(
        t => t.Gun == "Really Big");
    

    然后反编译并玩弄它......

    【讨论】:

    • 如何使用vehicleFunc?如何将此传递给 IQueryable 的 Where 子句?
    • @Jeonsoft var filtered = source.Where(vehicleFunc);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 2016-10-05
    • 1970-01-01
    相关资源
    最近更新 更多