Why do we need C# delegates

前端 未结 8 715
伪装坚强ぢ
伪装坚强ぢ 2020-12-22 20:06

I never seem to understand why we need delegates? I know they are immutable reference types that hold reference of a method but why can\'t we just call the method directly,

8条回答
  •  有刺的猬
    2020-12-22 20:48

    Because you may not have the method written yet, or you have designed your class in such a way that a user of it can decide what method (that user wrote) the user wants your class to execute.

    They also make certain designs cleaner (for example, instead of a switch statement where you call different methods, you call the delegate passed in) and easier to understand and allow for extending your code without changing it (think OCP).

    Delegates are also the basis of the eventing system - writing and registering event handlers without delegates would be much harder than it is with them.

    See the different Action and Func delegates in Linq - it would hardly be as useful without them.

    Having said that, no one forces you to use delegates.

提交回复
热议问题