Why do we need C# delegates

前端 未结 8 646
遥遥无期
遥遥无期 2020-12-22 19:47

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:28

    Of course you can call method directly on the object but consider following scenarios:

    1. You want to call series of method by using single delegate without writing lot of method calls.
    2. You want to implement event based system elegantly.
    3. You want to call two methods same in signature but reside in different classes.
    4. You want to pass method as a parameter.
    5. You don't want to write lot of polymorphic code like in LINQ , you can provide lot of implementation to the Select method.

提交回复
热议问题