c# - Action 委托(delegate)可以指向具有返回类型的方法吗?

标签 c# .net delegates

Action 委托(delegate)可以指向具有返回类型的方法吗? 例如

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

上面的代码可以编译。现在,如果我将上面的内容写成

Action a = new Action(Add);

这不会编译。谁能帮我理解这背后的逻辑?

最佳答案

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

在功能上等同于

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

Action a = new Action(ExecuteAdd); 会编译。

原因是 () => Add(); 实际上创建了一个 anonymous method .将其分配给 Action 类型的变量会推断出返回类型 void

关于c# - Action 委托(delegate)可以指向具有返回类型的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49261373/

相关文章:

c# - 异步函数 - 使用主线程拥有的对象进行回调

c# - 重定向到错误页面

c# - Liskov 替换和合成

c# - 如何在 C# 中使用 Dictionary<> 的聚合方法?

c# - 文档的“屏幕截图”

c# - Automapper 展开到列表

ruby-on-rails - 带有委托(delegate)和条件的事件记录

c# - 为什么 Delegate.CreateDelegate 允许无效转换?

c# - 如何从打开的流中检测文件重命名

C# 优先级队列