确定事件是否已附加到 [英] Determine if an event has been attached to yet

查看:113
本文介绍了确定事件是否已附加到的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个对象 - 一个包含一些代码将会触发一个事件,一个包含该事件的处理程序。因为第二个对象的实例还不存在,所以加载第一个对象中的AddHandler不能。当我提出我的事件时,我想检查一下object2的副本是否被实例化(容易做到),如果一个处理程序已经附加到事件(不知道该怎么做)。



我也可以另外建议如何做到这一点。如果我在Object1.Load中添加了AddHandler,并且Object2还不存在,那么即使稍后创建它也不会处理我的事件。现在,在触发事件的代码中,我刚刚使用了一个RemoveHandler,然后每次发生一个AddHandler,然后我知道当对象终于存在时,我会附加,但是我知道这个是一个糟糕的方法。



我看到一篇关于类似的文章(确定绑定到事件的事件处理程序列表),也许我在翻译中缺少某些东西,但是我无法使代码在我的自定义事件在VB.NET中。

解决方案

你也可以在挂钩事件之前检查一个bool字段。 >

 如果不是eventHooked然后
addhandler
eventHooked = true
结束如果

另外如果你需要一个很好的c#到vb转换器 http://www.tangiblesoftw issolutions.com/ 有一个可以自由翻译100行或更少或翻译1000行的项目。不仅如此,您必须购买它,但通常这些限制将正常工作。不,我不想为他们做广告: - )


I have two objects - one that contains some code with will fire an event, and one that contains the handler for that event. I can't "AddHandler" in the Load of the first object, because an instance of the second object doesn't exist yet. When I raise my event, I want to check to see if a copy of object2 has been instantiated (easy to do), and if a handler has been attached to the event yet (not sure how to do this).

I'm also open to another recommendation about how to do this instead. If I do my AddHandler in Object1.Load, and Object2 doesn't exist yet, then it will never handle my event, even if I create it later. Right now, in the code that fires the event, I've just resorted to doing a RemoveHandler and then an AddHandler every single time the event is raised, and then I know I'll attach when the object finally exists, but I know this is a crappy method.

I saw an article about something similar (Determine list of event handlers bound to event), and maybe I'm missing something in the translation, but I can't get the code to work on my custom event in VB.NET.

解决方案

You could also just have a bool field that you check before hooking the event.

if not eventHooked then
 addhandler
 eventHooked = true
end if

Also if you need a good c# to vb converter http://www.tangiblesoftwaresolutions.com/ has one that can translate a 100 lines on the fly or less for or translate a project of a 1000 lines for free. More than that you have to purchase it, but that usually those limits will work just fine. No I am not trying to advertise for them :-)

这篇关于确定事件是否已附加到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆