gpt4 book ai didi

c# - 无法分配给委托(delegate)具有不太具体的参数类型的匿名方法

转载 作者:可可西里 更新时间:2023-11-01 07:51:08 24 4
gpt4 key购买 nike

我能够分配一个方法 M 来委托(delegate)对象 d 具有不太具体的参数类型,但是当我想分配一个具有相同签名的匿名方法时作为 Md 的方法,我得到一个错误。

这是为什么?

class derivedEventArgs : EventArgs { }

delegate void newDelegate(object o, derivedEventArgs e);

static void Main(string[] args)
{
newDelegate d = M; // ok
d = (object o, EventArgs e) => { }; // error
}

public static void M(object o, EventArgs e) { }

最佳答案

C# 语言规范的第 6.5 节对此进行了介绍。如果您显式键入匿名函数的参数,则它们的类型和修饰符必须匹配才能成为兼容的签名。

Specifically, a delegate type D is compatible with an anonymous function F provided

...

If F has an explicitly typed parameter list, each parameter in D has the same type and modifiers as the corresponding parameter in F.

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com