Why can't I put a delegate in an interface?

前端 未结 7 1019
清歌不尽
清歌不尽 2021-02-01 03:24

Why can\'t I add a delegate to my interface?

相关标签:
7条回答
  • 2021-02-01 04:29

    As others have mentioned, you can only define delegates outside of the interface.

    There is little to nothing wrong w/ using delegates. Personally I think that Func<int, double> is less desirable than using delegates:

    1. You cannot name the arguments, so the argument meaning can be ambiguous
    2. It is old news that Events are not thread safe, thus the following code is not ideal:

      if (MyFuncEvent != null)
      {
          MyFuncEvent(42, 42.42);
      }
      

      See: http://kristofverbiest.blogspot.com/2006/08/better-way-to-raise-events.html

      The safer code is:

      MyFuncEventHandler handler = MyFuncEvent;
      if (handler != null)
      {
          handler(42, 42.42);
      }
      
    3. You have to duplicate the signature of the event if you want to save it to a variable (or you could use var, which I dislike). If you have lots of arguments then this could get very tedious (again, you could always be lazy and use var).

      Func<int, double, string, object, short, string, object> handler = MyFuncEvent;
      if (handler != null)
      {
          handler(42, 42.42, ...);
      }
      

    Delegates save you from having to duplicate the signature of the method/event every time you want to assign it to a variable type.

    0 讨论(0)
提交回复
热议问题