method('Using Lambda Expression.');

  Console.ReadLine();

 }

}

Lambda expressions are discussed in more detail in Chapter 14.

Events

One of the most important techniques in computer science that made today's graphical user interface operating systems (such as Windows, Mac OS X, Linux, and so on) possible is event-driven programming. Event- driven programming lets the OS react appropriately to the different clicks made by the user. A typical Windows application has various widgets such as buttons, radio buttons, and checkboxes that can raise events when, say, a user clicks them. The programmer simply needs to write the code to handle that particular event. The nice thing about events is that you do not need to know when these events will be raised — you simply need to provide the implementation for the event handlers that will handle the events and the OS will take care of invoking the necessary event handlers appropriately.

In .NET, events are implemented using delegates. An object that has events is known as a publisher. Objects that subscribe to events (in other words, handle events) are known as subscribers. When an object exposes events, it defines a delegate so that whichever object wants to handle this event will have to provide a function for this delegate. This delegate is known as an event, and the function that handles this delegate is known as an event handler. Events are part and parcel of every Windows application. For example, using Visual Studio 2008 you can create a Windows application containing a Button control (see Figure 7-4).

Figure 7-4

When you double-click the Button control, an event handler is automatically added for you:

public partial class Form1 : Form {

 public Form1() {

  InitializeComponent();

 }

 private void button1_Click(object sender, EventArgs e) {

 }

}

But how does your application know which event handler is for which event? Turns out that Visual Studio 2008 automatically wires up the event handlers in the code-behind of the form (FormName.Designer.cs; see Figure 7-5) located in a function called InitializeComponent ():

this.button1.Location = new System.Drawing.Point(12, 12);

this.button1.Name = 'button1';

this.button1.Size = new System.Drawing.Size(75, 23);

this.button1.TabIndex = 0;

this.button1.Text = 'button1';

this.button1.UseVisualStyleBackColor = true;

this.button1.Click += new System.EventHandler(this.button1_Click);

Figure 7-5

Notice that the way you wire up an event handler to handle the Click event is similar to how you assign a method name to a delegate.

Alternatively, you can manually create the event handler for the Click event of the Button control. In the Form() constructor, type += after the Click event and press the Tab key. Visual Studio 2008 automatically completes the statement (see Figure 7-6).

Figure 7-6

Press the Tab key one more time, and Visual Studio 2008 inserts the stub of the event handler for you (see Figure 7-7).

Figure 7-7 

The completed code looks like this:

public Form1() {

 InitializeComponent();

 this.button1.Click += new EventHandler(button1_Click);

}

void button1_Click(object sender, EventArgs e) {

}

Notice that Click is the event and the event handler must match the signature required by the event (in this case, the event handler for the Click event must have two parameter — object and EventArgs). By convention, event handlers in the .NET Framework return void and have two parameters. The first is the source of the event (that is, the object that raises this event), and the second is an object derived from EventArgs. The EventArgs parameter allows data to be passed from an event to the event handler. The EventArgs class is discussed further later in this chapter.

Using the new lambda expressions in C# 3.0, the preceding event handler can also be written like this:

public Form1() {

 InitializeComponent();

 this.button1.Click += (object sender, EventArgs e) => {

  MessageBox.Show('Button clicked!');

 };

}

Handling Events

Let's take a look at how to handle events using a couple of simple examples. The Timer class (located in the System.Timers namespace) is a class that generates a series of recurring events at regular intervals. You usually use the Timer class to perform some background tasks, such as updating a ProgressBar control when downloading some files from a server, or displaying the current time.

The Timer class has one important event that you need to handle — Elapsed. The Elapsed event is fired every time a set time interval has

Вы читаете C# 2008 Programmer's Reference
Добавить отзыв
ВСЕ ОТЗЫВЫ О КНИГЕ В ИЗБРАННОЕ

0

Вы можете отметить интересные вам фрагменты текста, которые будут доступны по уникальной ссылке в адресной строке браузера.

Отметить Добавить цитату