Example says. NET Event Usage

Source: Internet
Author: User

A summary

This article provides an example of how to use. NET events.


Demonstration of two examples

1 Create a new Windows application eventexp, as shown in the program structure.

Figure 1 program structure diagram

2 New Teacher class Teacher (class file is Teacher.cs), Teacher class is the event Publisher.

The detailed code for the teacher class is shown below.

/////  CLR Event sample Code/////  Author: March or May child ////DATE:2014/08/31////  http://blog.csdn.net/yl2isoft  //  //*****************************  using system;using System.Windows.Forms; namespace eventexp{public    class Teacher    {public        Teacher () {} public         event eventhandler<askeventargs> Ask;        public void Raise ()        {            MessageBox.Show ("mrwang:who are on duty Today");            Raisedutyinfo ();        }        private void Raisedutyinfo ()        {            eventhandler<askeventargs> ask = ask;            if (ask = null)            {                Ask (this, new Askeventargs ());    }}} public class Askeventargs:eventargs    {    }}

The teacher class defines an event ask that is of type eventhandler<askeventargs>, which is triggered in method raisedutyinfo and pops up to the form before the event is triggered "mrwang:who is on duty Today? " message box.

View the definition of the eventhandler<askeventargs> type as follows:

public delegate void Eventhandler<teventargs> (object sender, Teventargs e);

From the definition, you can see that,eventhandler<askeventargs> is essentially a delegate that uses a method with two parameters and does not have a return value, the first parameter is the object that contains the event publisher, and the second parameter provides the event- related information, the parameter must derive from the EventArgs class, which does not need to provide any event-related information in this instance, so the Askeventargs class does not contain any implementation code. The eventhandler<askeventargs> used in this example are defined by. NET, and of course we can define the types of events we need, and we'll have a chance to explore them later.

3 New Student class student (class file is Student.cs), Student class is the subscriber of the event.

The detailed code for the student class is shown below.

/////  CLR Event sample Code/////  Author: March or May child ////DATE:2014/08/31////  http://blog.csdn.net/yl2isoft  //  //*****************************  using System.Windows.Forms; namespace eventexp{public    class Student    {        private string name;        private bool isonduty;        Public Student (string name, bool isonduty)        {            this.name = name;            This.isonduty = isonduty;        }        public void Answer (object sender, Askeventargs e)        {            if (isonduty)            {                MessageBox.Show (string. Format ("{0}:{0} is on duty today!", name, name);            }            else            {                MessageBox.Show (string. Format ("{0}:{0} is not on duty today!", name, name));}}}    

The answer method of the student class satisfies the requirements of the eventhandler<askeventargs> delegate, so the method can act as an event-handling method for the Ask event of the teacher class.

4 The main screen of the program as shown in.

Figure 2 Program main screen

The back-end code for the main screen of the program is shown below.

//clr Event sample Code/////Author: March or May child////DATE:2014/08 /31////Http://blog.csdn.net/yl2isoft////************************************************************ using Syste M;using System.Windows.Forms;        namespace eventexp{public partial class Form1:form {Student Zhangsan;        Student LiSi;        Student Wangwu;        Student Tiana;         Teacher Mrwang;             Public Form1 () {InitializeComponent ();            Zhangsan = new Student ("Zhang San", true);            LiSi = new Student ("John Doe", true);            Wangwu = new Student ("Harry", true);            Tiana = new Student ("March or May child", false);            Mrwang = new Teacher ();            Subscribe to Events Mrwang.ask + = Zhangsan.answer;            Mrwang.ask + = Lisi.answer;            Mrwang.ask + = Wangwu.answer; Mrwang.ask + = Tiana.            Answer;            Unsubscribe Event Mrwang.ask-= Lisi.answer; Mrwang.ask-= Wangwu.        Answer;        } private void Button1_Click (object sender, EventArgs e) {mrwang.raise (); }    }}

In the Form1 class, instantiate the student class, get the Student object Zhangsan, LiSi, Wangwu and Tiana, first let all student objects Subscribe teacher Object Mrwang's Ask event, Then cancel the event subscription for Lisi and Wangwu two classmates. In this way, when the Mrwang ask event is triggered, Zhangsan and Tiana will execute their own event handling methods, and Lisi and Wangwu will not be able to perceive the Mrwang ask event to occur. Zhangsan and Tiana, in their own event handling method, will pop up a message box that says "Zhangsan:zhangsan is on duty today!" and "March or May child: March or May Son is not on duty today!".

5 The results of the program are as shown in the following steps, consistent with the analysis of the 4th step.

Figure 3 program Run

Three summary

The 1 event is delegate-based.

The 2 event programming model contains three parts of the event Publisher, the event Subscriber, and the subscription relationship between the two.

The 3 event programming model is an implementation of the observer pattern.

4 using the event programming model typically consists of the following steps:

  • defines the type parameters of the event ( Askeventargs Class)
  • defines the class of the event publisher ( Teacher Class)
  • The event is defined in the event Publisher's class ( Ask event for teacher Class)
  • The event notification method is defined in the event Publisher's class, the event is triggered in the method, and the method is triggered to execute the event-handling method ( Raisedutyinfo method of the teacher class)
  • defines the class of the event Subscriber ( Student Class)
  • The event- handling method is defined in the class of the event subscriber, and the definition of the method must satisfy the definition of the delegate used by the event ( Student Class of Answer method)
  • Subscribe to Events ( Form1 in the Pass " += "and" -= "Completion of the event subscription and cancellation of the subscription operation.")

Example says. NET Event Usage

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.