如果我有经典的注册和取消注册事件的方式(+ = - =),还有办法看看是否现在注册了某些内容吗?
假设我有两种方法可以在一个Timer上注册。如果已经在.Elapsed
注册了某些内容,我不想要任何其他内容进行注册(并且不希望多次注册)。
有没有办法查找当前为特定事件注册的方法?
答案 0 :(得分:5)
如果您真的想要这样的行为,我认为最好的选择是使用重载添加{}并删除事件的{}功能。
public class Foo
{
private EventHandler<ElapsedEventArgs> _elapsed;
public EventHandler<ElapsedEventArgs> Elapsed
{
add
{
if( _elapsed == null )
_elapsed += value;
else
throw new InvalidOperationException ("There is already an eventhandler attached to the Elapsed event.");
}
remove
{
_elapsed -= value;
}
}
}
答案 1 :(得分:1)
您可以使用GetInvocationList()并依次获取计数