.NET events - blocking subscribers from subscribing on an event

浪子不回头ぞ 提交于 2019-12-03 13:44:53
class EmptyProcessor : IProcessor {

    [Obsolete("EmptyProcessor.OnProcess should not be directly accessed", true)]
    public event EventHandler OnProcess { 
        add { throw new NotImplementedException(" :( "); }
        remove { }
    }
}

In this situation, the true parameter on Obsolete causes a compile-time exception. so:

EmptyProcessor processor1 = new EmptyProcessor();
IProcessor processor2 = new EmptyProcessor();

processor1.OnProcess += handler;  // <-- compile-time error
processor2.OnProcess += handler;  // <-- run-time error

You can implement it with custom add/remove methods but I believe this is a bad practice.

Look, you have an interface, a contract to be implemented by different classes.
OnProcess is part of this contract and is not special in any way.

One usually uses interfaces when she wants to work with different classes under the same set of operations. Interfaces allow you to code like this:

IProcessor proc = GetProcessorAnyhow ();
proc.DoSomething ();

without knowing concrete type at compile type.

However, with your approach,

IProcessor proc = GetProcessorAnyhow ();
proc.OnProcess += (sender, e) => { };

may fail without any apparent reason, although it looks like absolutely legitimate code.
Always make sure that wrong code looks wrong.

You may have done one of the following design mistakes:

  • Put OnProcess in IProcessor whereas it may not be each processor's contract;
  • Made EmptyProcessor implement IProcessor, whereas actually it can't satisfy the contract.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!