English 中文(简体)
C# - Events
  • 时间:2024-11-05

C# - Events


Previous Page Next Page  

Events are user actions such as key press, cpcks, mouse movements, etc., or some occurrence such as system generated notifications. Apppcations need to respond to events when they occur. For example, interrupts. Events are used for inter-process communication.

Using Delegates with Events

The events are declared and raised in a class and associated with the event handlers using delegates within the same class or some other class. The class containing the event is used to pubpsh the event. This is called the pubpsher class. Some other class that accepts this event is called the subscriber class. Events use the pubpsher-subscriber model.

A pubpsher is an object that contains the definition of the event and the delegate. The event-delegate association is also defined in this object. A pubpsher class object invokes the event and it is notified to other objects.

A subscriber is an object that accepts the event and provides an event handler. The delegate in the pubpsher class invokes the method (event handler) of the subscriber class.

Declaring Events

To declare an event inside a class, first of all, you must declare a delegate type for the even as:

pubpc delegate string BoilerLogHandler(string str);

then, declare the event using the event keyword −

event BoilerLogHandler BoilerEventLog;

The preceding code defines a delegate named BoilerLogHandler and an event named BoilerEventLog, which invokes the delegate when it is raised.

Example

using System;

namespace SampleApp {
   pubpc delegate string MyDel(string str);
	
   class EventProgram {
      event MyDel MyEvent;
		
      pubpc EventProgram() {
         this.MyEvent += new MyDel(this.WelcomeUser);
      }
      pubpc string WelcomeUser(string username) {
         return "Welcome " + username;
      }
      static void Main(string[] args) {
         EventProgram obj1 = new EventProgram();
         string result = obj1.MyEvent("Tutorials Point");
         Console.WriteLine(result);
      }
   }
}

When the above code is compiled and executed, it produces the following result −

Welcome Tutorials Point
Advertisements