c# - 无参数匿名方法可以分配给有参数委托(delegate)

标签 c# delegates anonymous-function anonymous-methods

class Program{
      static void Main(){
         test11 jhbee = Program.test;  //error
         test11 yep = delegate {  };   //no error

      }
   static void test() { }
}

delegate void test11(int r);

所以我有委托(delegate) test11 它返回 void 并接受 1 个参数。
当我尝试将无参数方法分配给test11的实例时,编译器显然会发出错误,但是当我分配无参数test11 实例的 >anonymous 方法,不会发出错误。
我的意思是,我可以看到它的工作没有任何障碍,但是你能告诉我为什么会这样吗?这有充分的理由吗?

最佳答案

来自documentation :

When you use the delegate operator, you might omit the parameter list. If you do that, the created anonymous method can be converted to a delegate type with any list of parameters

因此,虽然看起来是这样,但创建的匿名方法并不是真正的无参数 - 它的参数列表只是尚未定义。

至于为什么这是一个选项,this answer to a related question可能有助于解释它。

关于c# - 无参数匿名方法可以分配给有参数委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73839958/

相关文章:

c# - 跟踪更改(未保存)的对象

c# MSOffice Interop Word 不会杀死 winword.exe

c# - 无法将时间类型 System.TimeSpan 隐式转换为 'long'

wpf - Winforms 到 WPF 转换 : BeginInvoke to what?

matlab - 如何使用匿名函数实现不同操作的向量输入/输出?

Javascript 沙盒单元测试

c# - 我可以在 Visual Studio 中调试 C# 时提交对实际数据库的更改吗?

ios - 如何使用展开Segue将数据从第二个 View Controller 传递回第一个 View Controller ?

ios - UISplitViewController 中两个 View Controller 之间的通信

javascript - 将匿名函数更改为命名函数时如何添加额外参数