简体   繁体   中英

Assign lambda expression as a function in C#

I'm new to c# but coming from c++ we had something that you could do which is inline create lambda functions. I'm trying to something like this, but is not working. Can someone show me how to do something like this?

playButton.Click += (object sender, RoutedEventArgs e) => (getController.startPlay());

You may need to use a block for the body of the lambda in some cases, most notably when you need to execute multiple statements:

playButton.Click += (s, e) => { getController.startPlay(); Trace.Write("Play..."); };

For lambdas that really are just a single expression, you can omit the block (no need for the parentheses either). Eg:

Func<int> someDelegate = () => 42;

Your code should work except for one thing, when you add parenthesis, (...) , the part between has to be an expression , ie. "something that evalues to something "

So this:

... => (getController.startPlay());

will give you:

CS0201 Only assignment, call, increment, decrement, and new object expressions can be used as a statement

Note that even if the method returns something, it will then likely not automagically fit the delegate you're trying to use for the event, in which case there will be a similar error but a different cause, so making startPlay return a value won't work either.

In any case, to get it working you simply have to remove the parenthesis:

... => getController.startPlay();

The code should then work just as you expect it to.

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