我在使用.NET設計win窗體時使用了代表...即拖/放按鈕,雙擊並填寫myButton_click事件。我想了解如何在C#中創建和使用用戶定義的委託。用戶定義的代表如何在C#中使用和創建?
用戶定義的代表如何在C#中使用和創建?
我在使用.NET設計win窗體時使用了代表...即拖/放按鈕,雙擊並填寫myButton_click事件。我想了解如何在C#中創建和使用用戶定義的委託。用戶定義的代表如何在C#中使用和創建?
用戶定義的代表如何在C#中使用和創建?
我建議閱讀關於該主題的教程。
基本上,聲明委託類型:
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");
}
這是基本的用法。
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());
}
不太重複(找不到重複的),但很多在這裏SO信息,嘗試
Differnce between Events and Delegates上手,再看看
Whis is this delegate doing . . .
希望這些幫助
廣泛的答案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
+1,你忘記了在第一代碼 「委託」 關鍵字線。 – ybo 2009-03-06 09:19:42