WriteLine ("An event occurred");
}
...
Button button = new Button();
button.Text = "Click me";
button.Click += LogPlainEvent;
button.KeyPress += LogPlainEvent;
button.MouseClick += LogPlainEvent;
Form form = new Form();
form.AutoSize=true;
form.Controls.Add(button);
Application.Run(form);
We??™ve managed to completely remove the two handler methods that dealt specifically
with key and mouse events, using one event handling method B for everything. Of
course, this isn??™t terribly useful if you want to do different things for different types of
events, but sometimes all you need to know is that an event occurred and, potentially,
the source of the event. The subscription to the Click event C only uses the implicit
conversion we discussed in the previous section because it has a simple EventArgs
parameter, but the other event subscriptions D involve the conversion and contravariance
due to their different parameter types.
I mentioned earlier that the .NET 1.0/1.1 event handler convention didn??™t make
much sense when it was first introduced. This example shows exactly why the guidelines
are more useful with C# 2. The convention dictates that event handlers should
have a signature with two parameters, the first of which is of type object and is the
origin of the event, and the second of which carries any extra information about the
event in a type deriving from EventArgs.
Pages:
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294