c#-为什么此委托分配不起作用以及如何解决呢?
作者:互联网
我有以下示例代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.del = this.EventHandler; <-- This does not build
}
public void EventHandler(object sender, PropertyChangedEventArgs e)
{
}
public delegate void A(object sender, EventArgs e);
private A del;
}
它抱怨委托分配.我怀疑这是由于协方差/协方差问题引起的,说实话,这是我不完全了解的概念.
有什么办法可以构建此代码?我需要一个具有任何事件args的事件的通用处理程序(继承自EventArgs).
解决方法:
想象一下,该行已编译:
this.del = this.EventHandler;
然后,这是一个问题:
// since del must accept ANY EventArgs descendant, this should be possible:
del.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add));
// since del's signature IS (object, PropertyChangedEventArgs), we must convert
// NotifyCollectionChangedEventArgs to PropertyChangedEventArgs
// OOOPS...
I need a generic handler for any event with any event args
使用具有此签名的处理程序:
public void EventHandler(object sender, EventArgs e)
{
}
// compiles just fine
this.Loaded += EventHandler;
this.Closing += EventHandler;
this.Drop += EventHandler;
标签:delegates,covariance,contravariance,c,net 来源: https://codeday.me/bug/20191120/2040326.html