C# 从表达式调用方法

C# 从表达式调用方法,c#,lambda,C#,Lambda,当使用Expression.Call时,方法“Any”使用什么类型和参数 我有一个内在的和一个外在的表达,我想用在任何人身上。表达式是以编程方式构建的 内部(本工程): 这给了我两种表达方式: v => v.Tank t => t.Gun == "Really Big"; 我要找的是: v => v.Tank.Any(t => t.Gun == "Really Big"); 我正在尝试使用Expression.Call方法来使用“Any”。 1.这样做对吗? 2.下面

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

我有一个内在的和一个外在的表达,我想用在任何人身上。表达式是以编程方式构建的

内部(本工程):

这给了我两种表达方式:

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”方法与提供的参数不兼容。”

以下是我如何称呼任何人:

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

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

我在尝试使
字符串.Contains
工作时遇到了类似的问题;我只是使用了
GetMethod
/
MethodInfo
方法;然而,它是复杂的,因为它是一个通用的方法

这应该是正确的
MethodInfo
-但是如果不更加清楚
油箱和
车辆
,就很难给出完整的(可运行的)答案:

   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);
MethodInfo-method=typeof(Queryable).GetMethods()
.Where(m=>m.Name==“Any”&&m.GetParameters().Length==2)
.Single().MakeGenericMethod(类型(储罐));
ParameterExpression vehicleParameter=表达式参数(
(车辆)类型,“v”);
var vehicleFunc=表达式.Lambda(
表情,打电话(
方法,,
表达式.属性(
车辆参数表,
类型(车辆).GetProperty(“油箱”),
油箱功能),车辆参数);
如果有疑问,请使用reflector(并稍微调整一下;-p)-例如,我根据您的规范编写了一个测试方法:

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

反编译并玩弄它…

如何使用vehicleFunc?如何将其传递给IQueryable的Where子句?@Jeonsoft
var filtered=source.Where(vehicleFunc)
   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);
Expression<Func<Vehicle, bool>> func = v => v.Tank.Any(
    t => t.Gun == "Really Big");