C# [Understanding misunderstandings about event delegation]

event

Event (Event) is basically a user operation, such as key press, click, mouse movement, etc., or some prompt information, such as a notification generated by the system. The application needs to respond to events when they occur

Delegate is equivalent to defining a function type.

An event is an event built on a delegate, which is equivalent to defining a delegate function pointer (callback function pointer)

Events enable objects or classes to notify and execute methods of other classes.

principle:

For example, when the class bell rings, students enter the classroom and the teacher starts class.
Disassemble the elements
. Bell: Publisher.
Bell: Event triggers, publishing message.
Student teacher: Subscriber.
Entering the classroom and class: execution function of the event.

Misunderstanding codes need to be understood in reverse

What is said above is easy to understand and can be easily confused when it is mapped to the code.
Correspond with a requirement. Click
Add on the sub-page to refresh the parent page.
Publisher sub-page
defines events and delegates here.
When the trigger node is reached, all subscribers are notified.
The call here is best not to be understood as the call and execution of an ordinary function but as publishing information to all subscribers.

 刷新列表页数据的委托
        public event EventHandler ReloadList;
  当来到触发节点是 通知  所有的订阅者 

 ReloadList(this, new MyEventArg {
    
     query = PName.Text });
```csharp

Subscribers and subscriptions.
Binding of parent nodes and event execution functions.
The parent class can call the event function executed by the subclass for the event attachment of the subclass.
This should be understood as the parent class subscribing to the event of the subclass. The parent class agrees that when the subclass event occurs, Things you do.
For example, the teacher agrees to start class when the bell rings.

在父类内部 

childForm.ReloadList+= fatherFunc
       

Event function execution
is defined within the parent class to match the parameters of the delegate. Accepting event parameters is not a general method.

 private void LoadDocList(object sender, EventArgs e)
        {
    
    
            List<DocDetail> details;
            MyEventArg myEventArg1 = e as MyEventArg; 
            details = documentBLL.GetProDocDetail(myEventArg1.query);             gridControl1.DataSource = details;
        }

Because there can be multiple subscribers and different execution methods, any delegate whose parameters match the event definition can be added to the event for execution.

In general, it may be better to understand the code backwards

Guess you like

Origin blog.csdn.net/qq_43886548/article/details/129128451