Delegates vs Interfaces in C#

后端 未结 5 720
遇见更好的自我
遇见更好的自我 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:16

    Yes, delegates are in many ways like single-method interfaces. However:

    • There is support built into the CLR for them
    • There's support in the framework for them, including multi-cast abilities and asynchronous invocation
    • There's additional C#/VB language support in the form of method group conversions, lambda expressions, anonymous methods
    • They're mandated for events (i.e. events and delegates are a sort of matching pair)
    • They mean you don't need to implement an interface in a separate class for each delegate instance you want to create.

    The last point is the most important one - consider a LINQ expression of:

    var query = collection.Where(x => x > 5)
                          .Select(x => x * x);
    

    Now imagine if to express the logic of x > 5 and x * x you had to write a separate class for each expression, and implement an interface: the amount of cruft vs useful code would be ridiculous. Now of course the language could have been designed to allow conversions from lambda expressions into interface implementations via separate classes, but then you'd still lose the benefit of being able to simply write a separate method and create a delegate with that as the target. You'd also still lose the multi-cast abilities.

    As a similar thought exercsise, consider looping statements such as while and for. Do we really need them when we've got goto? Nope. But life is much better with them. The same is true of delegates - and indeed properties, events, etc. They all make the development simpler.

提交回复
热议问题