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/