简体   繁体   中英

Understanding the point of Delegates in C#

I have done a fair bit of reading and I am at the stage where I am beginning to grasp what they do, but am at a loss when it comes to why or where I would use them. In each example I've seen the recurring definition seems to be as a method pointer, and you can use this in place of a call to the method which is apparently useful when the developer doesn't know which method to call or the selection of a method is based on a condition or state.

This is where I struggle a bit, why can't I just have an if statement or a switch statement and then call the method directly based on the outcome? What's so bad about calling a method directly from an object instance? From my understanding a Delegate offers a better way to do this but I can't understand what's better about it, from my perspective it's just a round-about way to achieve the same thing an if statement could do when deciding which method to call.

I'm at a loss and have been rambling on for quite a bit now, any help at all on the matter would be greatly appreciated!

why can't I just have an if statement or a switch statement and then call the method directly based on the outcome?

This would be fine, if you had 2 or 3 different branches and methods. Now imagine having tens or hundreds of methods which can be potentially called depending on a situation. I wouldn't want to be the one to write that if statement.

Imagine having 100 different potential abilities for a character in a game. Each ability can have its own method to perform. Depending on what abilities a player has, you can just throw those methods into a list for that character using delegates. Now its fully customize-able, and player's abilities aren't hard-written into the code, they can be picked up or lost during the course of the game super easily, and there can be thousands of abilities not to mention the amount of potential combinations.

Think about it this way. According to SOLID principle of OOD (for example) every object should have responsibility over a single part of the functionality. Using this principle we can assume that:

Classes are responsible for working with custom objects, structs with - sets of data, methods are responsible for actions, events are responsible of signalizing that something happens and delegates are responsible for the corresponding action on this events that should take place.

Events and methods are ' busy ' with their own single part of the functionality and therefore cannot handle the events themselves and be responsible for methods. That's why we need delegates...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM