9 Subscribing to events with anonymous methods that ignore parameters
Neat trick for
events!
150 CHAPTER 5 Fast-tracked delegates
to call different method overloads) then the compiler needs more help. To show you
what I mean, let??™s look at how we start threads. There are four thread constructors in
.NET 2.0:
public Thread (ParameterizedThreadStart start)
public Thread (ThreadStart start)
public Thread (ParameterizedThreadStart start, int maxStackSize)
public Thread (ThreadStart start, int maxStackSize)
The two delegate types involved are
public delegate void ThreadStart()
public delegate void ParameterizedThreadStart(object obj)
Now, consider the following three attempts to create a new thread:
new Thread(delegate() { Console.WriteLine("t1"); } );
new Thread(delegate(object o) { Console.WriteLine("t2"); } );
new Thread(delegate { Console.WriteLine("t3"); } );
The first and second lines contain parameter lists??”the compiler knows that it can??™t convert
the anonymous method in the first line into a ParameterizedThreadStart, or convert
the anonymous method in the second line into a ThreadStart. Those lines compile,
because there??™s only one applicable constructor overload in each case. The third line,
however, is ambiguous??”the anonymous method can be converted into either delegate
type, so both of the constructor overloads taking just one parameter are applicable.
Pages:
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308