问题在于
Delegate
是不可变的。
如果你向事件添加一个处理程序,它会创建一个新的
Delegate
实例,其中包含旧处理程序和新添加的处理程序。旧的
Delegate
没有被修改并被丢弃。
当我写
value.AnEvent += AnEvent
时,它将包含当前处理程序(如果有)的
Delegate
添加到内部类的事件中。但是,对外部类事件的更改会被忽略,因为它们不会改变我添加到内部类事件中的
Delegate
实例。同样,如果我在设置
Inner
属性后删除处理程序,则该处理程序不会从内部类事件中删除。
有两种正确的方法来解决这个问题。
我可以创建自己的处理程序来调用包装器的事件,就像这样:
public event EventHandler AnEvent;
public OtherClass Inner {
get { }
set {
if(Inner != null)
Inner.AnEvent -= Inner_AnEvent;
if(value != null)
value.AnEvent += Inner_AnEvent;
}
}
void Inner_AnEvent(object sender, EventArgs e) {
var handler = AnEvent;
if (handler != null) handler(sender, e);
}
另一种方法是在包装器中创建自定义事件,并将其处理程序添加到内部类的事件中,如下所示:
另一种方法是在包装器中创建自定义事件,并将其处理程序添加到内部类的事件中,如下所示:
EventHandler anEventDelegates
public OtherClass Inner {
get { }
set {
if(value != null)
value.AnEvent += anEventDelegates;
}
}
public event EventHandler AnEvent {
add {
anEventDelegates += value;
if (Inner != null) Inner.AnEvent += value;
}
remove {
anEventDelegates -= value;
if(Inner != null) Inner -= value;
}
}
请注意,这并不完全是线程安全的。
我自己解决了这个问题,并为有类似问题的人发布了问题和答案。