Delegates vs Interfaces in C#

后端 未结 5 641
遇见更好的自我
遇见更好的自我 2021-01-30 00:37

I would like to pose this question as long as I am trying currently to dig into the use and the purpose of delegates, although it is likely to have been asked in similar formula

5条回答
  •  太阳男子
    2021-01-30 01:14

    The only real advantages of delegates over interfaces are

    1. Delegates could deal with different argument types even before .Net supported generics.
    2. A class can create delegates exposing multiple different methods sharing the same signature; replacing delegates with interfaces would mean that every class could expose one method that implemented each delegate-style interface without creating helper classes, but would need a helper class for each additional implementation.

    When .net did not support generics, delegates were essential part of it since declaring distinct non-generic interfaces for each and every different function signature one would want to pass would have been unworkable. If .net had supported generics from the beginning, delegates would not have been necessary except for certain scenarios involving Reflection, and even there it would perhaps have been most useful to have the type Action be an implementation of IAction (so that code which simply needs something it can Invoke would use the interface). An interface-based approach would have required the creation of single-method classes in cases where classes need to create delegates exposing multiple methods, but would have eliminated the need to create separate delegate instances in the many common cases where the number of methods of a given signature to be exposed is precisely one.

    Incidentally, replacing delegates with interfaces would in no way prevent the creation of a general-purpose Combine method. Indeed, interface covariance could make such a method work better than the existing Delegate.Combine in many respects. Implementing a method analogous to Delegate.Remove would be at best clunky and annoying, but I can think of no situation other than event subscription management which would require the use of Delegate.Remove, and event subscription could best be handled using other approaches anyway.

提交回复
热议问题