WithEvents/Handles better than Remove/AddHandler?

拟墨画扇 提交于 2019-11-29 13:35:49

It depends on what you're trying to achieve. If you have several event handlers which must handle events for various controls during the lifetime of a form/object then WithEvents and Handles is the easiest way to go. The language will do all of the dirty work for you in terms of setting up the event. On the other hand, if you tend to disconnect from events during the lifetime of the form, AddHandler and RemoveHandler are better options.

I prefer WithEvents/Handles in situations where it is applicable, because it better expresses what the code is supposed to be doing. One caveat with "WithEvents/Handles" is that any object which receives events from a longer-lived object should implement IDisposable and should set all its WithEvents variables to Nothing when it is disposed, to ensure all events are unwired. Detaching events when using AddHandler/RemoveHandler is just as necessary, but perhaps more obvious. When using WithEvents it's somewhat easier to forget.

BTW, I don't know of any way to automatically set all WithEvents variables to Nothing. It would seem a common enough requirement, but for whatever reason Microsoft didn't include such a feature in VB.

Depends what your doing really, if you want to dynamically attach / detach event handlers then using AddHandler/RemoveHandler is the way to go about it otherwise using Handles is perfectly fine.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!