2009年2月8日 星期日

The Delegate of C#

中文版

What the hell is Delegate? Let's read about it on MSDN: "A delegate is a type that defines a method signature, and can be associated with any method with a compatible signature. You can invoke (or call) the method through the delegate. Delegates are used to pass methods as arguments to other methods. Event handlers are nothing more than methods that are invoked through delegates." Hum~, it's a little bit hard to get it straight! Let's take another shot on MSDN: "A delegate is a reference type that can be used to encapsulate a named or an anonymous method. Delegates are similar to function pointers in C++; however, delegates are type-safe and secure." All right, forget about the definition of it, let's try the example codes provided on MSDN. We might get a rough idea of it: // Declare delegate -- defines required signature: // Any methods that instantiated with it has to match it's signature: // A parameter of double is required and returns a double. delegate double MathAction(double num); class DelegateTest { // Regular method that matches signature: static double Double(double input) { return input * 2; } static void Main() { // Instantiate delegate with named method: // "ma" in the next line is "similar to function pointers in C++" , expressed  previously. MathAction ma = Double; // Invoke delegate ma: // The express "ma(4.5)" is identical to "Double(4.5)" double multByTwo = ma(4.5); Console.WriteLine(multByTwo); // Instantiate delegate with anonymous method: // The concept of anonymous method is similar to the previous one. MathAction ma2 = delegate(double input) { return input * input; }; double square = ma2(5); Console.WriteLine(square); // Instantiate delegate with lambda expression MathAction ma3 = s => s * s * s; double cube = ma3(4.375); Console.WriteLine(cube); } } The example code above is executable directly! All you need is creating a Console Application of C#, and then paste the example to the file Program.cs; Be aware of the first line "using System;" that was generated automatically while new project was creating. It is necessary for running the example correctly.

1 則留言:

quinlysabala 提到...

Borgata Hotel Casino & Spa - JamBase
Borgata Hotel Casino & 동해 출장안마 Spa features the 김포 출장샵 largest casino floor, featuring more than 영천 출장샵 2000 slot machines and 70 table games. Borgata 고양 출장안마 Hotel Casino & Spa has been in operation 충청남도 출장샵 since