gpt4 book ai didi

c# - 注册事件,为什么代码可以编译不报错?

转载 作者:行者123 更新时间:2023-11-30 18:45:32 27 4
gpt4 key购买 nike

我相信应该有很多关于 SO 的问题与此相关,但我想不出合适的关键字来搜索它们。

代码

class Subscriber
{
public Subscriber(Notifier n)
{
n.OnSomeEvent += (object sender, EventArgs e) => { }; //This does not compile
n.OnSomeEvent += ReactOnEvent; //This compile successfully!
}

private void ReactOnEvent(object sender, EventArgs e)
{

}
}

class Notifier
{
public event EventHandler<MyEventArgs> OnSomeEvent;
public void Trigger()
{
OnSomeEvent?.Invoke(this, new MyEventArgs());
}
}

class MyEventArgs : EventArgs
{

}

注册 lambda 表达式的编译错误是有道理的。

Error CS1661 Cannot convert lambda expression to delegate type 'EventHandler<MyEventArgs>' because the parameter types do not match the delegate parameter types

Error CS1678 Parameter 2 is declared as type 'System.EventArgs' but should be 'ConsoleApplication1.MyEventArgs'

但是为什么编译器没有给我同样的错误呢?我对事件处理的理解从根本上是错误的吗?我认为编译器要求事件签名及其处理程序匹配

n.OnSomeEvent += ReactOnEvent;

编辑:这个问题的答案

正如彼得在他的评论中指出的,并引自 ms docs ,

(starting with .NET 3.5)...you can assign to delegates not only methods that have matching signatures, but also methods that return more derived types (covariance) or that accept parameters that have less derived types (contravariance) than that specified by the delegate type.

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