我可以将lambda表达式数组传递给具有params参数的方法吗? [英] Can I pass an array of lambda expressions to a method with a params argument?
问题描述
我想调用一个这样的方法:
I want to call a method like this:
签名: void方法(对象a,对象b,params LambdaExpression []表达式) ;
调用:方法(a,b,x => xA,x => xB) / code>
call: Method(a, b, x => x.A, x => x.B)
可以吗?
我们假设'x'的类型是一个恒定类型。例如,如果x => xA和y => yB是Funcs,则它们将是 Func< TType,*>
,使得params数组总是相同键入 TType
,但返回值的类型 *
可能会在params数组的元素之间不同。这就是为什么我不得不选择像LambdaExpression一样更通用的东西作为类型,但是我不知道是否会有效。我可以在运行时解压缩方法中的表达式,但是当他们的两个泛型类型参数之一不同时,我很难在表达式中传递表达式。
Let's assume that the type of 'x' is a constant type. For example, if x => x.A and y => y.B were Funcs, they'd be Func<TType,*>
, such that the params array always had the same type for TType
, but the return value's type *
could differ from element to element of the params array. That's why I had to choose something more generic like LambdaExpression as the type, but I don't know if that will work. I can unpack the expression within the method at runtime, but I'm having a hard time just trying to pass expressions to a method when one of their two generic type parameters differ.
这样就可以了,即使我不得不这样称呼:方法(a,b,(Type x)=> xA,(Type x)=> xB)
It would be fine, even if I had to call it more like: Method(a, b, (Type x) => x.A, (Type x) => x.B)
推荐答案
你可以只是编译器的帮助,将你的代码转换成表达式(与编译它)使用泛型只要。所以你必须
You can but the compiler assist that will turn your code to expression(vs compiling it) works with generics only. So you have to
Expression<Func<TType, AType>> expr1 = x => x.A;
Expression<Func<TType, BType>> expr2 = x => x.B;
Method(a, b, expr1, expr2);
或投入内线
Method(a, b, (Expression<Func<TType, AType>>) (x => x.A), expr2)
或使用更通用的参数类型
or use a more generic type of argument
void Method(object a, object b, params Expression<Func<object, object>>[] expressions)
这篇关于我可以将lambda表达式数组传递给具有params参数的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!