gpt4 book ai didi

c# - 从表达式调用方法

转载 作者:太空狗 更新时间:2023-10-30 00:29:24 25 4
gpt4 key购买 nike

使用 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);

这给了我 2 个表达式:

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?

最佳答案

我在尝试获取 string.Contains 时遇到了类似的问题上类;我刚刚使用了 GetMethod/MethodInfo相反的办法;然而 - 它很复杂,因为它是一种通用方法......

这应该是对的MethodInfo - 但如果不更清楚地说明 Tank 就很难给出完整的(可运行的)答案和 Vehicle :

   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");

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

关于c# - 从表达式调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/439172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com