Can I pass an array of lambda expressions to a method with a params argument?

送分小仙女□ 提交于 2019-12-12 04:36:12

问题


I want to call a method like this:

signature: void Method(object a, object b, params LambdaExpression[] expressions);

call: Method(a, b, x => x.A, x => x.B)

Is it possible?

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.

It would be fine, even if I had to call it more like: Method(a, b, (Type x) => x.A, (Type x) => x.B)


回答1:


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

or cast inline

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)


来源:https://stackoverflow.com/questions/43814829/can-i-pass-an-array-of-lambda-expressions-to-a-method-with-a-params-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!