C#学习:委托
- 委托声明和实例化
(1)通过与委托签名相同的方法的方法名声明实例化委托
//声明委托 public delegate void Del(string message); //与委托签名相同的方法 //签名相同即参数列表相同,返回值类型相同 public static void DelegateMethod(string message) { Console.WriteLine(message); } //通过与委托签名相同的方法实例化委托 Del handler = DelegateMethod; //调用委托 handler("hello world");
(2)通过匿名方法声明实例化委托
public delegate void Del(string message); Del del=delegate(string name){ Console.WriteLine("Hello:" + name); }; del("delegate");
(3)通过 Lambda 表达式声明和实例化委托
public delegate void Del(string message); Del del = name =>{Console.WriteLine("Hello:{0}", name);}; del("delegate");
- 委托使用
(1)调用委托。调用方传递给委托的参数被传递给方法,方法如果有返回值由委托返回给调用方。
class Program { public delegate int Add(int a, int b); public static int AddMethod(int a, int b) { int c = a + b; Console.WriteLine("{0}+{1}={2}", a, b, c); return c; } static void Main(string[] args) { Add add = AddMethod; int c = AddMethod(1, 1); Console.WriteLine("result:{0}", c); Console.Read(); } }
输出:1+1=2
result:2
(2)异步回调委托。委托实例作为方法的参数使用,在该方法内使用委托无须关注委托对应方法的具体实现,该功能类似接口。
class Program { public delegate int Add(int a, int b); public static int AddMethod(int a, int b) { int c = a + b; Console.WriteLine("{0}+{1}={2}", a, b, c); return c; } static void Main(string[] args) { Add add = AddMethod; int d = AddWithCallBack(1, 1, add); Console.WriteLine("result:{0}", d); Console.Read(); } public static int AddWithCallBack(int a, int b, Add callback) { int c = callback(a, b); return c; } }
输出:1+1=2
result:2
(3)多路广播委托。调用委托时,可以调用多个方法,如果向委托方法列表中添加方法,可以通过加法运算符或加法赋值运算符(“+”或“+=”)添加委托实例。也可以通过减法运算符或减法赋值运算符(“-”或“-=”)移除方法。在多路广播委托中,委托将按顺序调用方法,方法引起的更改对下一个方法是可见的,在一个方法内发生异常,将不再调用后边的方法。
class Program { public delegate void Del(string message); public static void DelegateMethod(string message) { Console.WriteLine(message); } static void Main(string[] args) { MethodClass obj = new MethodClass(); Del del1 = obj.Method1; Del del2 = obj.Method2; Del del3 = DelegateMethod; Del allMethodsDelegate = del1 + del2; allMethodsDelegate += del3; allMethodsDelegate("Delegate Test1"); allMethodsDelegate -= del1; allMethodsDelegate("Delegate Test2"); Console.Read(); } } public class MethodClass { public void Method1(string message) { Console.WriteLine("Method1:" + message); } public void Method2(string message) { Console.WriteLine("Method2:" + message); } }
输出:Method1:Delegate Test1
Method2:Delegate Test1
Delegate Test1
Method2:Delegate Test2
Delegate Test2
- MSDN委托使用实例
// 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 TestBookDB { // Print the title of the book. static void PrintTitle(Book b) { System.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: System.Console.WriteLine("Paperback Book Titles:"); // Create a new delegate object associated with the static // method Test.PrintTitle: bookDB.ProcessPaperbackBooks(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(totaller.AddBookToTotal); System.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); } } } /* Output: Paperback Book Titles: The C Programming Language The Unicode Standard 2.0 Dogbert's Clues for the Clueless Average Paperback Book Price: $23.97 */