Further understanding of delegates and events through a WPF instance

Source: Internet
Author: User

wrote in front of "talking about delegates in C #" and "talking about events in C #" Two blogs, the content is somewhat abstract, it seems difficult to explain the relationship between delegates and events.

Today, a small program is used to further illustrate the use and connection of the two.

Start by creating a new WPF application named Testdelegateandevent.
Add the four buttons to the. Xmal, adding a window_loaded event.

The code is as follows:

<window x:class="Testdelegateandevent.mainwindow" xmlns="http// Schemas.microsoft.com/winfx/2006/xaml/presentation " xmlns:x=" http://schemas.microsoft.com/ Winfx/2006/xaml " Title=" MainWindow " Height=" = " Width= "525" Loaded="window_loaded">     <Grid>         <button  Content  =< Span class= "Hljs-value" > "execute delegate"  height  = "39"  horizontalalignment  = "left"  margin  = "128,53,0,0"   Name  = "button1"  verticalalignment  =< Span class= "Hljs-value" > "Top"  width  = "254"  click  = "button1_click" />          <button  Content  =< Span class= "Hljs-value" > "disturbance delegate"  height  = "39"  horizontalalignment  = "left"  margin  = "128,118,0,0"  name  = "Button2"  verticalalignment  = "Top"  width  = "254"   Click  = "button2_click" />          <button  Content  =< Span class= "hljs-value" > "execution event"  height  = "39"  horizontalalignment  = "left"  margin  = "128,181,0,0"  name  = "Button3"  verticalalignment  = "Top"  width  = "254" />          <button Content="Interference event" Height=" HorizontalAlignment" ="Left" Margin="128,241,0,0" Name="Button4"  VerticalAlignment="Top" Width="254" />     </Grid> </Window>

The next step is to write the. cs Code:
A delegate is defined and the delegate is mounted on a function

 Public classtest{ Public Delegate void MyDelegate();//Create a Delegate instance     PublicMyDelegate Mydel; }test Test =NewTest (); Public MainWindow() {InitializeComponent ();}//Method a Public void fun_a() {MessageBox.Show ("A method has triggered"); }//Method B Public void Fun_b() {MessageBox.Show ("The B method triggered the"); }//Method C Public void Fun_c() {MessageBox.Show ("The C method triggered the"); }Private void window_loaded(Objectsender, RoutedEventArgs e) {//Registration Delegate (Mount method)Test.mydel + = fun_a; Test.mydel + = Fun_b; }Private void Button1_Click(Objectsender, RoutedEventArgs e) {Test.mydel (); }Private void button2_click(Objectsender, RoutedEventArgs e) {Test.mydel =NULL;  Test.mydel + = Fun_c; }

Run the above code, click Execute Delegate, pop up two MessageBox. Click on the interference delegate, then click on the execution of the delegate, pop up a messagebox, that is, only the "C method is triggered." As we can see, everything is caused by Mydel = null.

A delegate essence is a class that contains a pair of useful fields, the first field is a reference to the object, the second field holds a pointer to a method, so we can interpret the delegate as a pointer to a function, and when a method assigns a value to a delegate, the delegate points to the first address of the method. That is, the method name, so when we give the delegate to register a A, a, a two method, the delegate points to the first address of a A, a two method, but this is suddenly assigned to the delegate, and assigned a null object, note here is the assignment symbol [=], which means that the delegate clears the original pointer pointing, At this point, it points to a null, and then the delegate registers the C method, so the delegate points to null and the first address of the C method, which is why the runtime only sees the reason the C method is triggered!

That is to say now the delegate becomes unsafe, which day a project to entrust a lot of methods of registration, but suddenly be disturbed, the front of the registration is invalid, then we do the work is not white, there is no way to prevent this interference?? The answer is, of course, that you should have guessed that it is time for the event to play.

We rewrite the code to add the event.
Add code to the Window_Loaded function:
Test. Eventmydel + = fun_a;
Test. Eventmydel + = Fun_b;
When we add code Test.eventmydel = NULL in Button4_Click, the compiler will error:
Error CS0070: Event "TestDelegateAndEvent.MainWindow.Test.EventMyDel" can only appear to the left of + = or-= (from type " TestDelegateAndEvent.MainWindow.Test, except when used in the.
This indicates that the = operator is not allowed to subscribe in the event.

 Public classtest{ Public Delegate void MyDelegate();//Create a Delegate instance     PublicMyDelegate Mydel;//Declare an event     Public EventMyDelegate Eventmydel;//Event triggering mechanism (must and event in the same class) cannot be used to trigger an event directly from Eventmydel ()     Public void Doeventdel() {Eventmydel ()}}test Test =NewTest (); Public MainWindow() {InitializeComponent ();}//Method a Public void fun_a() {MessageBox.Show ("A method has triggered"); }//Method B Public void Fun_b() {MessageBox.Show ("The B method triggered the"); }//Method C Public void Fun_c() {MessageBox.Show ("The C method triggered the"); }Private void window_loaded(Objectsender, RoutedEventArgs e) {//Registration Delegate (Mount method)Test.mydel + = fun_a;     Test.mydel + = Fun_b; Test.    Eventmydel + = fun_a; Test. Eventmydel + = Fun_b;}Private void Button1_Click(Objectsender, RoutedEventArgs e) {Test.mydel (); }Private void button2_click(Objectsender, RoutedEventArgs e) {Test.mydel =NULL;  Test.mydel + = Fun_c; }Private void Button3_Click(Objectsender, RoutedEventArgs e) {test.  Doeventmydel (); }Private void Button4_Click(Objectsender, RoutedEventArgs e) {test. Eventmydel + =NULL; Test. Eventmydel + = Fun_c; }

As you can see from the above code, a delegate can use "=", whereas an event cannot use "=". That is, an event is a encapsulation of a delegate, and it is like the relationship between a property and a field.

In this case, special attention should be paid to the above error, if the test class is not written, that is not encapsulated. Then if you register an event with code that is in the same class as the event-related code, use "=" is OK, the following code will not error!!!
That

     Public Delegate void MyDelegate();//Create a Delegate instance     PublicMyDelegate Mydel;//Declare an event     Public EventMyDelegate Eventmydel;//Event triggering mechanism (must and event in the same class) cannot be used to trigger an event directly from Eventmydel ()     Public void Doeventdel() {Eventmydel ()} Public MainWindow() {InitializeComponent ();}//Method a Public void fun_a() {MessageBox.Show ("A method has triggered"); }//Method B Public void Fun_b() {MessageBox.Show ("The B method triggered the"); }//Method C Public void Fun_c() {MessageBox.Show ("The C method triggered the"); }Private void window_loaded(Objectsender, RoutedEventArgs e) {//Registration Delegate (Mount method)Mydel + = fun_a; Mydel + = Fun_b;//Register eventEventmydel + = fun_a; Eventmydel + = Fun_b;}Private void Button1_Click(Objectsender, RoutedEventArgs e) {Mydel (); }Private void button2_click(Objectsender, RoutedEventArgs e) {Mydel =NULL;  Mydel + = Fun_c; }Private void Button3_Click(Objectsender, RoutedEventArgs e) {Doeventmydel (); }Private void Button4_Click(Objectsender, RoutedEventArgs e) {Eventmydel =NULL;//** will not error * *Eventmydel + = Fun_c; }

"'

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Further understanding of delegates and events through a WPF instance

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.