检查事件是否已注册

Off*_*ler 6 c# events

如果我有经典的方式注册和取消注册事件(+ = - =),还有一种方法可以查看是否立即注册了某些内容吗?

假设我有两种方法可以在一个Timer上注册.如果已经注册了某些内容.Elapsed,我不想要任何其他内容进行注册(并且不希望多次注册).

有没有办法查找当前注册的特定事件的方法?

Fre*_*els 5

如果你真的想要这样的行为,我认为最好的选择是使用重载add {}和remove {}功能.

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;
       }
   }

}
Run Code Online (Sandbox Code Playgroud)

  • 是的,但把它变成NOP是有争议的.投掷可能更合适. (4认同)