The difference between commission and event, explain it all at once

TextCtrl.xaml

  <Grid>
        <StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center" Height="68">
            <Button Width="100" Margin="10" Content="清除" x:Name="btnClear"/>
            <Button Width="100" Margin="10" Content="恢复" x:Name="btnRecall"/>
        </StackPanel>
    </Grid>

TextCtrl.xaml.cs

  public partial class TextCtrl : UserControl
    {
        public TextCtrl()
        {
            InitializeComponent();         
            this.btnClear.Click +=this.clearClick;
            this.btnRecall.Click += this.recalClick;
        }
        public event Action<string,string> clearEvent;
        public event Action<string,string> recallEvent;
        public Action clear_delegate;
        public Action recall_delegate;

        private void clearClick(object sender, RoutedEventArgs e)
        {
            if (clearEvent != null) { clearEvent("clear", "event"); }//没有Invoke()方法
            if (clear_delegate != null) { clear_delegate.Invoke(); }//有Invoke()方法
        }

        private void recalClick(object sender, RoutedEventArgs e)
        {
            if (recallEvent != null) { recallEvent("recall","event"); }//没有Invoke()方法
            if (recall_delegate != null) { recall_delegate.Invoke(); }//有Invoke()方法
        }
      
    }

 

MainWindow.xaml

<Grid>
        <StackPanel Orientation="Vertical" >         
            <TextBox Width="200" Height="45" HorizontalAlignment="left" Margin="10" x:Name="txtBox" />
            <local:TextCtrl HorizontalAlignment="Left" Margin="10 0 10 0"  x:Name="textCtrl"/>
            <TextBlock x:Name="txtBlock" Height="Auto" Width="Auto" Foreground="Red" FontSize="14"/>
        </StackPanel>
    </Grid>

MainWindwo.xaml.cs

  public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.textCtrl.clearEvent += TextCtrl_clearEvent;
            this.textCtrl.recallEvent += TextCtrl_recallEvent;
            // this.textCtrl.clearEvent += new Action<string,string> (TextCtrl_clearEvent);//也可以这么写
            // this.textCtrl.recallEvent +=new Action<string,string>( TextCtrl_recallEvent);//也可以这么写
            // this.textCtrl.clearEvent = TextCtrl_clearEvent; //报错
            // this.textCtrl.recallEvent = TextCtrl_recallEvent; //报错


            this.textCtrl.clear_delegate += textBlockClear;
            this.textCtrl.recall_delegate += textBlockRecall;
            // this.textCtrl.clear_delegate += new Action(textBlockClear);//也可以这么写
            //this.textCtrl.recall_delegate += new Action(textBlockRecall);//也可以这么写
            // this.textCtrl.clear_delegate = textBlockClear;//不报错
            // this.textCtrl.recall_delegate = textBlockRecall;//不报错

        }
        private string text;
        public string Text 
          { get
            { 
               return text;
            }
           set{
                text = value;
             } 
        }

        private void TextCtrl_recallEvent(string arg1, string arg2)
        {
            txtBox.Text = Text;
        }

        private void TextCtrl_clearEvent(string arg1, string arg2)
        {         
            Text = txtBox.Text;
            txtBox.Clear();
        }
        private void textBlockClear()
        {
            txtBlock.Text = "Clear";
        }

        private void textBlockRecall()
        {
            txtBlock.Text = "Recall";
        }
    }

 

After being modified by event , you can write this custom event on xaml

  <local:TextCtrl HorizontalAlignment="Left" Margin="10 0 10 0"  x:Name="textCtrl" clearEvent="TextCtrl_clearEvent"  recallEvent="TextCtrl_recallEvent"/>

running result:

Explanation part:

1. The concept of delegation

1. Concept: Delegate (delegation, agent...): Delegate is actually a program feature, and its special feature is that delegate is used to express methods. In other words, the delegate is the representative of the method and the pointer of the method.

int age=10; age is actually a representative of 10.

Course myCourse = new Course(); myCourse is a representative of a specific object.

Delegate type Delegate variable = specific method (it can be one or multiple). The variables of the delegate method.

2. Why use delegation?

Imagine in life, for example, we do a thing, but we can not directly complete it. But we can do it for us through others.

    I--->Other people (delegated)--->Do things

   Through the comparison just now, we found that the previous age, myCourse, etc. represent some kind of "static data."

   Delegates represent "behavior", that is, method.

In software development, we will also encounter a similar situation, that is, we want to call a behavior (method) but this method is because in different objects,

We may not be able to call it directly, and then we can use delegates.

  Under normal circumstances: In object A, object B is created. At this time, if there is a public behavior C in object B, then we can call it in A.

 class A
{

      B b=new B();

     void MyMethod()
     {
             b.C();
    }

     void NewMethod(){}
}

Question: Is it okay if B wants to call the behavior NewMethod in A? Of course not! But it is possible through commission.


2. Basic use of commission

1. Declare the delegate (define the prototype of the method: the return value type of the method, the parameter type and the number of the method)

2. Write specific methods according to commission

3. Create a delegate variable (the delegate is a reference type)

4. Associate the delegate variable with one or more specific methods that conform to the delegate definition.

5. Use specific methods through delegate variables (not directly use methods)

Conclusion: By delegating variables, you can easily call the specific methods associated with it.

Extension: If we associate multiple methods to delegate variables at the same time, when we use delegate variables, the methods will be called in sequence in the order in which you associate them.

          The above is what we often call "multi-way delegation or multicast delegation".

Benefit: We can not only dynamically increase the association of the delegate to the method, but also dynamically remove the association of the method.

3. Commissioned actual combat application (1): Use in multi-form communication

1. In the main form A, several objects of the sub form B are created.

     Now Form B needs to call a method in A. Normally, this is not possible. But it can be achieved through delegation.


2. Tip: When we use delegates to complete tasks, the trick to define delegate variables is: define them wherever they are used! (Who uses who creates)

     The association between delegated variables and specific methods is usually separate. Generally, the association is made where the specific method is defined.


总结: B1->A     B2->A   B3->A

Extension: How to realize the broadcast of messages through delegation?

         Where to receive the message, write the method of receiving the message where! Here is Form B.

         
Four, commissioned actual combat application (two): to solve the problem of switching when the container is embedded in the form

5. Event (compared with delegate)

Just find one: this.btnCreateChildForm.Click += new System.EventHandler(this.btnCreateChildForm_Click);

public event EventHandler Click

public delegate void EventHandler(object sender, EventArgs e);

By observing the event of the button, I found that the event is actually a further package of the delegate.

Define events: (Look at the code directly) In the case, we achieve the same functions as before, but this time through events.

Event concept: An event is actually a message response mechanism generated by the object's stimulation of external information.

Essence: The event is actually a further packaging of the delegation.

Participants of the event:

[1] Sender: It is the object itself. When its information status changes, an event is triggered and all receivers are notified to receive it.

 passMsgEvent(this.txtSendMsg.Text, this.Text);

[2] Receiver (Receiver): is the event handler, this code will be automatically executed after the event sender is triggered.

       private void ReceiveMsg(string msg, string childName)
        {
            this.txtContent.Text += $"来自:{childName} 的消息:{msg}\r\n";
        }

The difference between events and delegates:

First, events cannot be assigned directly, such as event=null; compilation errors will occur, but delegates can.

           Benefit: Avoid direct user manipulation of events, such as Click events. If Click=null is allowed, the underlying code will be cleared! Can play a protective role.

                     Commissioning is relatively too "open".

Second, the event object has no invoke() method and can only be run by using parentheses.


Selection of delegates and events:

First, to solve the problem normally, there is no essential difference between using delegates and events. Therefore, our recommendation is to use delegation.

Second, if we are doing secondary development of controls and extending the events of controls, events must be used.

 

 

Guess you like

Origin blog.csdn.net/qq_41617901/article/details/110297691