简体   繁体   English

将Lambda表达式分配为C#中的函数

[英]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. 我是C#的新手,但是来自c ++的我们可以做的事情是内联创建lambda函数。 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: 在某些情况下,您可能需要为lambda的主体使用一个块,尤其是当您需要执行多个语句时:

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). 对于实际上只是一个表达式的lambda,您可以省略该块(也不需要括号)。 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 CS0201仅赋值,调用,递增,递减和新对象表达式可以用作语句

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. 请注意,即使该方法返回了某些内容,也可能无法自动适应您要用于该事件的委托,在这种情况下,会出现类似的错误,但原因不同,因此,使startPlay返回值不会也不行。

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. 然后,代码应该可以按您期望的方式工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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