Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

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

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...