2009-03-06 14 views

回答

8

我建議閱讀關於該主題的教程。

基本上,聲明委託類型:

public delegate void MyDelegate(string message); 

然後你就可以分配和直接調用它:

MyDelegate = SomeFunction; 
MyDelegate("Hello, bunny"); 

或者你創建一個事件:

public event MyDelegate MyEvent; 

然後你可以像這樣從外部添加事件處理程序:

SomeObject.MyEvent += SomeFunction; 

Visual Studio對此很有幫助。輸入+ =後,只需按Tab鍵,它將爲您創建處理程序。

然後你可以從對象中觸發事件:

if (MyEvent != null) { 
    MyEvent("Hello, bunny"); 
} 

這是基本的用法。

+0

+1,你忘記了在第一代碼 「委託」 關鍵字線。 – ybo 2009-03-06 09:19:42

1
public delegate void testDelegate(string s, int i); 

private void callDelegate() 
{ 
    testDelegate td = new testDelegate(Test); 

    td.Invoke("my text", 1); 
} 

private void Test(string s, int i) 
{ 
    Console.WriteLine(s); 
    Console.WriteLine(i.ToString()); 
} 
1

廣泛的答案mohamad halabi通過檢查article。 對於較短的答案檢查從C此略作修改例如:/ Program Files文件/微軟的Visual Studio 9.0 /樣品/ 1033 /文件夾...

using System; 
using System.IO; 


namespace DelegateExample 
{ 
    class Program 
    { 
    public delegate void PrintDelegate (string s); 

    public static void Main() 
    { 
     PrintDelegate delFileWriter = new PrintDelegate (PrintFoFile); 
     PrintDelegate delConsoleWriter = new PrintDelegate (PrintToConsole); 
     Console.WriteLine ("PRINT FIRST TO FILE by passing the print delegate -- DisplayMethod (delFileWriter)"); 

     DisplayMethod (delFileWriter);  //prints to file 
     Console.WriteLine ("PRINT SECOND TO CONSOLE by passing the print delegate -- DisplayMethod (delConsoleWriter)"); 
     DisplayMethod (delConsoleWriter); //prints to the console 
     Console.WriteLine ("Press enter to exit"); 
     Console.ReadLine(); 

    } 

    static void PrintFoFile (string s) 
    { 
     StreamWriter objStreamWriter = File.CreateText(AppDomain.CurrentDomain.BaseDirectory.ToString() + "file.txt"); 
     objStreamWriter.WriteLine (s); 
     objStreamWriter.Flush(); 
     objStreamWriter.Close(); 
    } 


    public static void DisplayMethod (PrintDelegate delPrintingMethod) 
    { 
     delPrintingMethod("The stuff to print regardless of where it will go to") ; 
    } 

    static void PrintToConsole (string s) 
    { 
     Console.WriteLine (s);  
    } //eof method 
    } //eof classs 
} //eof namespace 
相關問題