2009年5月14日 星期四

Delegate在C#中,是幹麼用的?

// A simple delegate example. 
   
using System;
   
// Declare a delegate. 
delegate string strMod(string str);
   
class DelegateTest {
  // Replaces spaces with hyphens.
  static string replaceSpaces(string a) {
    Console.WriteLine("Replaces spaces with hyphens.");
    return a.Replace(' ', '-');
  } 
   
  // Remove spaces.
  static string removeSpaces(string a) {
    string temp = "";
    int i;
   
    Console.WriteLine("Removing spaces.");
    for(i=0; i < a.Length; i++)
      if(a[i] != ' ') temp += a[i];
   
    return temp;
  } 
   
  // Reverse a string.
  static string reverse(string a) {
    string temp = "";
    int i, j;
   
    Console.WriteLine("Reversing string.");
    for(j=0, i=a.Length-1; i >= 0; i--, j++)
      temp += a[i];
   
    return temp;
  }
    
  public static void Main() { 
    // Construct a delegate.
    strMod strOp = new strMod(replaceSpaces);
    string str;
/* 
注意這邊,replaceSpaces這個function被當成strMod的參數傳進來,
這樣就完成委派,之後對strOp傳參數進去,就等同於對replaceSpaces傳參數
*/
   
    // Call methods through the delegate.
    str = strOp("This is a test.");
/*
所以當strOp在這邊傳入This is a test.的時候,相當於replaceSpaces("This is a test.")
會輸出 Resulting string: This-is-a-test.
*/
    Console.WriteLine("Resulting string: " + str);
    Console.WriteLine();
     
    strOp = new strMod(removeSpaces);
/* 現在又改註冊removeSpaces這個function */

    str = strOp("This is a test.");
    Console.WriteLine("Resulting string: " + str);
/* 會輸出 Resulting string: Thisisatest. */
    Console.WriteLine();
   
    strOp = new strMod(reverse);
    str = strOp("This is a test.");
    Console.WriteLine("Resulting string: " + str);
  }
}

The output from the program is shown here:

Replaces spaces with hyphens.
Resulting string: This-is-a-test.
   
Removing spaces.
Resulting string: Thisisatest.
   
Reversing string.
Resulting string: .tset a si sihT

參考書目
C#: The Complete Reference
by Herbert Schildt 
McGraw-Hill/Osborne © 2002 (933 pages) Citation
ISBN:9780072134858
Learn all aspects of the C# programming language that support the .NET Framework with this all-inclusive guide.
chapter 15 : Delegates and Events

沒有留言:

張貼留言