如何获得事件的订阅者? [英] How do I get the subscribers of an event?
本文介绍了如何获得事件的订阅者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将一个事件的订阅者复制到另一个事件.我可以获取事件的订阅者吗(比如返回委托的 MyEvent[0])?
I need to copy the subscribers of one event to another event. Can I get the subscribers of an event (like MyEvent[0] returning a delegate)?
如果这是不可能的,我将使用 add 访问器将委托添加到列表中.这会是最好的解决方案吗?
If this is not possible I would use the add accessor to add the delegates to a list. Would that be the best solution?
推荐答案
C# 事件/委托是多播的,因此委托是本身一个列表.从班级内部,要获得个别来电者,您可以使用:
C# events/delegates are multicast, so the delegate is itself a list. From within the class, to get individual callers, you can use:
if (field != null)
{
// or the event-name for field-like events
// or your own event-type in place of EventHandler
foreach(EventHandler subscriber in field.GetInvocationList())
{
// etc
}
}
但是,要一次性全部赋值,只需使用 += 或直接赋值:
However, to assign all at once, just use += or direct assignment:
SomeType other = ...
other.SomeEvent += localEvent;
这篇关于如何获得事件的订阅者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文