简体   繁体   English

动作委托可以指向具有返回类型的方法吗?

[英]Can action delegates point to methods having a return type?

Can action delegates point to methods having a return type? 动作委托可以指向具有返回类型的方法吗? For eg 例如

Action a = () => Add();  
int Add()
{
  return 5 + 6;
}

The above code compiles. 上面的代码编译。 Now if I write the above something like 现在如果我写上面的东西就像

Action a = new Action(Add);

This does not compile. 这不编译。 Could anyone please help me to understand the logic behind this? 有谁能帮助我理解这背后的逻辑?

Action a = () => Add();  
int Add()
{
  return 5 + 6;
}

is functionally equivalent to 在功能上等同于

Action a = ExecuteAdd;
int Add()
{
  return 5 + 6;
}
void ExecuteAdd() 
{
  Add();
}

And Action a = new Action(ExecuteAdd); 并且Action a = new Action(ExecuteAdd); would compile. 会编译。

The reason being that () => Add(); 原因是() => Add(); actually creates an anonymous method . 实际上创建了一个匿名方法 Assigning it to a variable of type Action infers the return type void . 将它分配给Action类型的变量会推断返回类型为void

First example creates an anonymous method that calls Add . 第一个示例创建一个调用Add的匿名方法。

Action a = () => Add();
           ^        
Anonymous method with void return type.

If you want to assign method to Action you should do this: 如果要将方法分配给Action ,则应执行以下操作:

Action a = Add;

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

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