C#教程的代表和榜樣
C# 委託允許像對像一樣使用方法. 這意味著您可以將該方法作為參數傳遞給其他方法. 這是通過將委託指向方法並將委託作為參數傳遞來完成的. 然後使用委託,您可以調用委託指向的方法.
委託的有用部分是可以將方法從一個對像傳遞到另一個對象.
我們知道,方法代表對象可以執行的某種類型的操作. 該操作是在聲明該方法的類中的方法定義本身中實現的. 通過委託實現類中包含的方法或部分方法, 可以委託給另一個類.
這裡, 我們有一個簡單的例子來理解委託. 我們有一個 Playlist 類,允許將歌曲添加到播放列表中. Playlist 類提供了一個名為 ShowPlaylist 的方法,可以打印出播放列表中的所有歌曲.
類播放列表
{
// code eliminated for brevity
public void ShowPlaylist()
{
foreach (歌曲在this.list中)
{
控制台.WriteLine("歌曲名稱: {0}". 歌曲名稱);
}
}
}
使用 Playlist 類 ShowPlaylist 方法將打印完整的播放列表.
讓我們向 Playlist 類引入代表. 使用委託將允許 Playlist 類的使用者實現顯示播放列表的邏輯.
這裡我們在 Playlist 類中聲明一個委託,它有一個 Song 類型的參數
類播放列表
{
// 為簡潔起見刪除了代碼
// delegate for showing song
public delegate bool ProcessPlaylistDelegate(歌歌);
...
我們需要調整ShowPlayList() 使用 ProcessPlaylistDelegate 的方法. ShowPlayList方法將ProcessPlaylistDelegate作為參數. 現在我們可以在打印之前處理播放列表.
//show the playlist using another function attached to ProcessPlaylistDelegate
public void ShowPlaylist(處理播放列表委託處理播放列表)
{
foreach (歌曲在this.list中)
{
如果 (處理播放列表(歌曲))
{
控制台.WriteLine("歌曲名稱: {0}", 歌曲名稱);
}
}
}
現在,只要返回類型和參數類型與委託匹配,該類就可以將任何處理委託給另一個方法. Program 類下面使用 Playlist 類. 我們聲明一個新的 Playlist.ProcessPlaylistDelegate,然後將 getMp3Songs 附加到該委託.
班級計劃
{
靜態無效主要(細繩[] 參數)
{
播放列表 playlist1 = 新播放列表();
//add some songs to the playlist
//use the delegate to process the list before it is printed on the screen
playlist1.ShowPlaylist(新的 Playlist.ProcessPlaylistDelegate(獲取Mp3歌曲));
}
}
下面是 getMp3Songs 方法定義. 該方法僅返回mp3歌曲. 因此 ShowPlaylist 將只打印 mp3 歌曲.
公共靜態 bool GetMp3Songs(歌歌)
{
//more logic goes here
return (歌曲.格式== "mp3");
}
當我們可以以不同的方式處理播放列表而不必接觸 Playlist 類時,委託的力量就會發揮作用. 下面我們聲明 2 Program 類中的其他方法.
公共靜態 bool GetCdSongs(歌歌)
{
//more logic goes here
return (歌曲.格式== "光盤");
}
公共靜態 bool GetAllSongs(歌歌)
{
//more logic goes here
return true;
}
Now we just need to attach these to the delegates in the Main method. These methods will process the playlist differently. The first method will only include cd songs and the second method will include all the songs. This is just a simple example but we can add as much processing as we require without having to touch the class Playlist.
playlist1.ShowPlaylist(新的 Playlist.ProcessPlaylistDelegate(GetCdSongs)); playlist1.ShowPlaylist(新的 Playlist.ProcessPlaylistDelegate(GetAllSongs));
