当前位置:  开发笔记 > 编程语言 > 正文

"自定义事件"如何在VB.Net中运行?

如何解决《"自定义事件"如何在VB.Net中运行?》经验,为你挑选了2个好方法。

在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

请帮忙.



1> Tom Anderson..:

VB为您提供了大量的工作.

简单地宣布一个事件:

Public Event DidSomething(sender as object, e as EventArgs)

然后在代码中的任何地方,调用下降的Raise事件

RaiseEvent DidSomething(me, EventArgs.Empty)



2> TcKs..:

委托是不可变的,因此方法"[Delegate] .Combine"返回新委托,但不修改参数.所以你需要:

_MyEvent = [Delegate].Combine(_MyEvent, value)

推荐阅读
手机用户2502851955
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有