An analysis of events in C #

Source: Internet
Author: User

Having spoken of the Commission, had to speak of the incident.

Events are based on delegates and provide a publish/subscribe mechanism for delegates.

Classes or objects can notify them through events when other classes or objects of interest occur. The class that sends (or raises) an event is called the publisher, and the class that receives (or processes) The event is called a Subscriber.

In a typical C # Windows form or WEB application, you can subscribe to events raised by controls such as buttons and list boxes. You can use the Visual C # integrated development Environment (IDE) to browse events published by a control and select the events to process. The IDE automatically adds the empty event handler method and the code that subscribes to the event.

The encapsulation of the delegate when the event occurs.

Event to help resolve delegation encapsulation issues. The event is located at the top of the delegate and provides the encapsulation so that the target source can only listen and not have full control of the delegate object.

Shows the appearance of the event:-

Understanding Events:

The button is a class and the Click event is triggered when you click on it.

A timer is a class that is triggered by a tick event per millisecond.

Here's an example of the application of the event.

Defines two classes of Cardealer and consumer. The Cardealer class provides an event that triggers when a new car arrives, and the consumer class subscribes to the event to get a notification of the arrival of the new car.

Event Publisher: The Cardealer class provides a EventHandler type of Newcarinfo event. An event typically uses a method with two parameters. The first parameter is an object that contains the sender of the event, and the second parameter provides information about the event.

You may be surprised that you don't define a delegate to define an event?? In fact, with the generic delegate EventHandler delegate, it is no longer necessary to delegate.

The syntax for EventHandler is as follows:

public delegate void EventHandler(Object sender,TEventArgs e) where TEventArgs : EventArgs

EventHandler defines a handler that returns void and accepts two parameters. The first argument must be object, the second argument is the T type, and for t there is a constraint that it must derive from the base class EventArgs. The Carinfoeventargs of the following code derives from the base class EventArgs.

EventArgs is the base class for the class that contains the event data, which does not contain event data and is used by events that do not pass state information to the event handler when the event is raised. If the event handler requires state information, the application must derive a class from this class to hold the data. The standard signature of an event handler delegate defines a method that has no return value, the type of the first argument is Object, it references the instance that raised the event, and the second argument derives from the EventArgs type, which holds the event data. If the event does not generate event data, the second parameter is just an instance of EventArgs. Otherwise, the second argument is a custom type derived from EventArgs, providing all the fields or properties required to hold the event data.

EventHandler is a predefined delegate that represents an event handler method for an event, regardless of whether the event generated event data. If the event does not generate event data, replace the generic type parameter with EventArgs, otherwise, provide your own custom event data type and replace the generic type parameter with that type.

The advantage of using EventHandler is that if events generate event data, you do not need to write your own custom delegate code. In addition, the. NET Framework requires only one implementation to support EventHandler, regardless of the event data type that overrides the generic type parameter.

Using System;Using System.Collections.Generic;Using System.Linq;Using System.Text;Namespacetestevent{PublicClassCarinfoeventargs:eventargs{Public Carinfoeventargs(StringCar) {This. car = car;}PublicString car{GetPrivateSet;}}Publicclass cardealer{public event eventhandlernewcarinfo; public  void  Newcar ( String Car) {Console.WriteLine ( " Cardealer. New Car {0} ", car); if (newcarinfo! = null) {Newcarinfo ( this, new Carinfoeventargs (Car));}}}      

Event Listener: The consumer class acts as an event listener. This class subscribes to the events of the Cardealer class and defines the Newcarishere method, which satisfies the requirements of the EventHandler delegate, whose parameter types are object and Carinfoeventargs.

Using System;Using System.Collections.Generic;Using System.Linq;Using System.Text;Namespacetestevent{Classconsumer{PrivateString name;Public consumer ( string Name) {this.name = name;} public  void  Newcarishere (object sender, Carinfoeventargs e) { Console.WriteLine ( "{0}: Car {1} is new", Name, E.car);}}       

Now you need to connect the event Publishers and Subscribers. Use "+ =" to create a subscription. The subscription was canceled with "-=". Using code:

Using System;Using System.Collections.Generic;Using System.Linq;Using System.Text;Namespacetestevent{Classprogram{Staticvoid Main (String[] (args) {var dealer =New Cardealer ();var Michael =New Consumer ("Michael");d Ealer. Newcarinfo + = Michael. Newcarishere;dealer. Newcar ("Mercedes");var Nick =New Consumer ("Nick");d Ealer. Newcarinfo + = Nick. Newcarishere;dealer. Newcar ("Ferrari");d Ealer. Newcarinfo-= Michael. Newcarishere;dealer. Newcar ("Toyota");}}}/*-------------------------------------output Result: Cardealer.NewCar MercedesMichael: Car MercedesIs  newcardealer. new car ferrariMichaelis newnick is newcardealer. new car toyotaNick: Car Toyota is new ---------------------------------------*/        

An analysis of events in C #

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.