Understanding events and event handlers in C#

后端 未结 12 1698
野性不改
野性不改 2020-11-22 04:06

I understand the purpose of events, especially within the context of creating user interfaces. I think this is the prototype for creating an event:

public vo         


        
12条回答
  •  猫巷女王i
    2020-11-22 04:36

    Another thing to know about, in some cases, you have to use the Delegates/Events when you need a low level of coupling !

    If you want to use a component in several place in application, you need to make a component with low level of coupling and the specific unconcerned LOGIC must be delegated OUTSIDE of your component ! This ensures that you have a decoupled system and a cleaner code.

    In SOLID principle this is the "D", (Dependency inversion principle).

    Also known as "IoC", Inversion of control.

    You can make "IoC" with Events, Delegates and DI (Dependency Injection).

    It's easy to access a method in a child class. But more difficult to access a method in a parent class from child. You have to pass the parent reference to the child ! (or use DI with Interface)

    Delegates/Events allows us to communicate from the child to the parent without reference !

    In this diagram above, I do not use Delegate/Event and the parent component B has to have a reference of the parent component A to execute the unconcerned business logic in method of A. (high level of coupling)

    With this approach, I would have to put all the references of all components that use component B ! :(

    In this diagram above, I use Delegate/Event and the component B doesn't have to known A. (low level of coupling)

    And you can use your component B anywhere in your application !

提交回复
热议问题