c# 中的委托類似于 c 或 c++ 中的函數指針。使用委托使程序員可以將方法引用封裝在委托對象內。然后可以將該委托對象傳遞給可調用所引用方法的代碼,而不必在編譯時知道將調用哪個方法。與 c 或 c++ 中的函數指針不同,委托是面向對象、類型安全的,并且是安全的。
委托聲明定義一種類型,它用一組特定的參數以及返回類型封裝方法。對于靜態方法,委托對象封裝要調用的方法。對于實例方法,委托對象同時封裝一個實例和該實例上的一個方法。如果您有一個委托對象和一組適當的參數,則可以用這些參數調用該委托。
委托的一個有趣且有用的屬性是,它不知道或不關心自己引用的對象的類。任何對象都可以;只是方法的參數類型和返回類型必須與委托的參數類型和返回類型相匹配。這使得委托完全適合“匿名”調用。
此教程包括兩個示例:
示例 1 展示如何聲明、實例化和調用委托。
示例 2 展示如何組合兩個委托。
此外,還討論以下主題:
委托和事件
委托與接口
示例 1
下面的示例闡釋聲明、實例化和使用委托。bookdb 類封裝一個書店數據庫,它維護一個書籍數據庫。它公開 processpaperbackbooks 方法,該方法在數據庫中查找所有平裝書,并為每本書調用一個委托。所使用的 delegate 類型稱為 processbookdelegate。test 類使用該類輸出平裝書的書名和平均價格。
委托的使用促進了書店數據庫和客戶代碼之間功能的良好分隔。客戶代碼不知道書籍的存儲方式和書店代碼查找平裝書的方式。書店代碼也不知道找到平裝書后將對平裝書進行什么處理。
// bookstore.cs
using system;
// a set of classes for handling a bookstore:
namespace bookstore
{
using system.collections;
// describes a book in the book list:
public struct book
{
public string title; // title of the book.
public string author; // author of the book.
public decimal price; // price of the book.
public bool paperback; // is it paperback?
public book(string title, string author, decimal price, bool paperback)
{
title = title;
author = author;
price = price;
paperback = paperback;
}
}
// declare a delegate type for processing a book:
public delegate void processbookdelegate(book book);
// maintains a book database.
public class bookdb
{
// list of all books in the database:
arraylist list = new arraylist();
// add a book to the database:
public void addbook(string title, string author, decimal price, bool paperback)
{
list.add(new book(title, author, price, paperback));
}
// call a passed-in delegate on each paperback book to process it:
public void processpaperbackbooks(processbookdelegate processbook)
{
foreach (book b in list)
{
if (b.paperback)
// calling the delegate:
processbook(b);
}
}
}
}
// using the bookstore classes:
namespace booktestclient
{
using bookstore;
// class to total and average prices of books:
class pricetotaller
{
int countbooks = 0;
decimal pricebooks = 0.0m;
internal void addbooktototal(book book)
{
countbooks += 1;
pricebooks += book.price;
}
internal decimal averageprice()
{
return pricebooks / countbooks;
}
}
// class to test the book database:
class test
{
// print the title of the book.
static void printtitle(book b)
{
console.writeline(" {0}", b.title);
}
// execution starts here.
static void main()
{
bookdb bookdb = new bookdb();
// initialize the database with some books:
addbooks(bookdb);
// print all the titles of paperbacks:
console.writeline("paperback book titles:");
// create a new delegate object associated with the static
// method test.printtitle:
bookdb.processpaperbackbooks(new processbookdelegate(printtitle));
// get the average price of a paperback by using
// a pricetotaller object:
pricetotaller totaller = new pricetotaller();
// create a new delegate object associated with the nonstatic
// method addbooktototal on the object totaller:
bookdb.processpaperbackbooks(new processbookdelegate(totaller.addbooktototal));
console.writeline("average paperback book price: ${0:#.##}",
totaller.averageprice());
}
// initialize the book database with some test books:
static void addbooks(bookdb bookdb)
{
bookdb.addbook("the c programming language",
"brian w. kernighan and dennis m. ritchie", 19.95m, true);
bookdb.addbook("the unicode standard 2.0",
"the unicode consortium", 39.95m, true);
bookdb.addbook("the ms-dos encyclopedia",
"ray duncan", 129.95m, false);
bookdb.addbook("dogbert's clues for the clueless",
"scott adams", 12.00m, true);
}
}
}
輸出
paperback book titles:
the c programming language
the unicode standard 2.0
dogbert's clues for the clueless
average paperback book price: $23.97
代碼討論
聲明委托 以下語句:
public delegate void processbookdelegate(book book);
聲明一個新的委托類型。每個委托類型都描述參數的數目和類型,以及它可以封裝的方法的返回值類型。每當需要一組新的參數類型或新的返回值類型時,都必須聲明一個新的委托類型。
實例化委托 聲明了委托類型后,必須創建委托對象并使之與特定方法關聯。與所有其他對象類似,新的委托對象用 new 表達式創建。但創建委托時,傳遞給 new 表達式的參數很特殊:它的編寫類似于方法調用,但沒有方法的參數。
下列語句:
bookdb.processpaperbackbooks(new processbookdelegate(printtitle));
創建與靜態方法 test.printtitle 關聯的新的委托對象。下列語句:
bookdb.processpaperbackbooks(new
processbookdelegate(totaller.addbooktototal));
創建與對象 totaller 上的非靜態方法 addbooktototal 關聯的新的委托對象。在兩個例子中,新的委托對象都立即傳遞給 processpaperbackbooks 方法。
請注意一旦創建了委托,它所關聯到的方法便永不改變:委托對象不可改變。
調用委托 創建委托對象后,通常將委托對象傳遞給將調用該委托的其他代碼。通過委托對象的名稱(后面跟著要傳遞給委托的參數,括在括號內)調用委托對象。下面是委托調用的示例:
processbook(b);
示例 2
本示例演示組合委托。委托對象的一個有用屬性是,它們可以“+”運算符來組合。組合的委托依次調用組成它的兩個委托。只可組合相同類型的委托,并且委托類型必須具有 void 返回值。“-”運算符可用來從組合的委托移除組件委托。
// compose.cs
using system;
delegate void mydelegate(string s);
class myclass
{
public static void hello(string s)
{
console.writeline(" hello, {0}!", s);
}
public static void goodbye(string s)
{
console.writeline(" goodbye, {0}!", s);
}
public static void main()
{
mydelegate a, b, c, d;
// create the delegate object a that references
// the method hello:
a = new mydelegate(hello);
// create the delegate object b that references
// the method goodbye:
b = new mydelegate(goodbye);
// the two delegates, a and b, are composed to form c,
// which calls both methods in order:
c = a + b;
// remove a from the composed delegate, leaving d,
// which calls only the method goodbye:
d = c - a;
console.writeline("invoking delegate a:");
a("a");
console.writeline("invoking delegate b:");
b("b");
console.writeline("invoking delegate c:");
c("c");
console.writeline("invoking delegate d:");
d("d");
}
}
輸出
invoking delegate a:
hello, a!
invoking delegate b:
goodbye, b!
invoking delegate c:
hello, c!
goodbye, c!
invoking delegate d:
goodbye, d!
委托和事件
委托非常適合于用作事件(從一個組件就該組件中的更改通知“偵聽器”)。
委托與接口
委托和接口的類似之處是,它們都允許分隔規范和實現。多個獨立的作者可以生成與一個接口規范兼容的多個實現。類似地,委托指定方法的簽名,多個作者可以編寫與委托規范兼容的多個方法。何時應使用接口,而何時應使用委托呢?
委托在以下情況下很有用:
調用單個方法。
一個類可能希望有方法規范的多個實現。
希望允許使用靜態方法實現規范。
希望類似事件的設計模式。
調用方不需要知道或獲得在其上定義方法的對象。
實現的提供程序希望只對少數選擇組件“分發”規范實現。
需要方便的組合。
接口在以下情況下很有用:
規范定義將調用的一組相關方法。
類通常只實現規范一次。
接口的調用方希望轉換為接口類型或從接口類型轉換,以獲得其他接口或類。注冊會員,創建你的web開發資料庫,