在C#中,如果我想创建一个"自定义事件",你可以这样做:
private EventHandler _MyEvent; Public Event EventHandler MyEvent { add{ _MyEvent += value; } remove{ _MyEvent -= Value; } } protected void RaiseMyEvent() { if(_MyEvent != nul) _MyEvent(this, EventArgs.Empty); }
在VB中,这不是那么简单,我也无法在网上找到任何帮助.这不起作用:
private _MyEvent as EventHandler Public Custom Event MyEvent as EventHandler AddHandler(ByVal value as EventHandler) _MyEvent += value 'does not work addhandler _MyEvent, value 'does not work [Delegate].Combine(_MyEvent, value) '_MyEvent still nothing End AddHandler RemoveHandler(ByVal value as EventHandler) 'Same kind of stuff here End RemoveHandler RaiseEvent(sender as Object, e as EventArgs) if(_MyEvent IsNot Nothing) Then '_MyEvent is always nothing _MyEvent.Invoke(sender, e) End If End RaiseEvent End Event
请帮忙.
VB为您提供了大量的工作.
简单地宣布一个事件:
Public Event DidSomething(sender as object, e as EventArgs)
然后在代码中的任何地方,调用下降的Raise事件
RaiseEvent DidSomething(me, EventArgs.Empty)
委托是不可变的,因此方法"[Delegate] .Combine"返回新委托,但不修改参数.所以你需要:
_MyEvent = [Delegate].Combine(_MyEvent, value)