如何从所属类外部检查事件处理程序的成员身份? [英] How to check membership of an event handler from outside the owning class?

查看:71
本文介绍了如何从所属类外部检查事件处理程序的成员身份?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题询问是否有一种方法来查找是否该代码已经向事件添加了自己的事件处理程序.但是,给出的答案只能在拥有该事件的同一类内部进行. ( Delegate.GetInvocationList 和其他.)

This question asks if there is a way to find if the code has already added its own event handler to an event. However, the answers given only work from inside the same class that own the event. (Delegate.GetInvocationList and others.)

我想向 AppDomain.CurrentDomain.AssemblyResolve 添加自定义事件处理程序.在再次添加我的自定义处理程序之前,是否有办法找出它是否已添加? (针对此事件和其他标准库事件.)

I want to add a custom event handler to AppDomain.CurrentDomain.AssemblyResolve. Is there a way to find out if my custom handler is already added before adding it again? (For this and other standard library events.)

如果答案确实是那是不可能的".然后请给出答案.

If the answer is indeed "That's impossible." then please give that as an answer.

推荐答案

那是不可能的.

基本上,您对外部事件的唯一操作是订阅"和取消订阅".

Basically, the only operations you have with an event from the outside are "subscribe" and "unsubscribe".

现在,您可以始终取消订阅,然后再进行订阅.如果指定的处理程序还不是该事件的处理程序,则取消订阅是不可操作的.如果您确定总是 这样做,那么您肯定会只订阅了一个处理程序.确实确实意味着您需要谨慎地进行在任何地方订阅-因此,理想情况下,请将代码放在一个位置.

Now you could always unsubscribe before you subscribe. Unsubscribing is a no-op if the specified handler isn't already a handler for the event. If you make sure you always do that, then you'll definitely have exactly one handler subscribed. It does mean you need to be careful to do that everywhere you subscribe though - so ideally, put that code in one place.

(或者,只需更改您的事件订阅,就可以轻松地告诉您只订阅一次...)

(Alternatively, just change your event subscription so that you can easily tell that you'll only ever subscribe once...)

这篇关于如何从所属类外部检查事件处理程序的成员身份?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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