简体   繁体   中英

Creating and applying a lambda in a single line in C#

I hope this isn't a silly question, but is there any way of achieving the following sort of thing in C#?

int y = (x => x * x)(9);

I know I can do this:

delegate int Transformer(int x);
Transformer square = x => x * x;
int y = square(9);

But is there any way to do the same thing more concisely? If not, is there a good reason why not?

Because a lambda is not associated with a delegate type, you need to specify the delegate type when you define a lambda, either on the left hand side or on the right hand side.

This should do the trick:

int result = new Transformer(x => x * x)(9);

The same thing more concisely:

int x = 9;
int result = x * x;

You can do this:

int y = ((Func<int,int>)(x => x * x))(9);

or use it an a delegate creation expression:

int y = new Func<int,int>(x => x * x)(9);

It's not terribly useful though...

(I've used Func<int, int> as an alternative to your Transformer delegate, to use the built-in delegate types where possible.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM