舉例講授C#編程中拜托的實例化應用。本站提示廣大學習愛好者:(舉例講授C#編程中拜托的實例化應用)文章只能為提供參考,不一定能成為您想要的結果。以下是舉例講授C#編程中拜托的實例化應用正文
歸並拜托
本示例演示若何創立多播拜托。 拜托對象的一個有效屬性是:可使用 + 運算符將多個對象分派給一個拜托實例。多播拜托包括已分派拜托的列表。在挪用多播拜托時,它會按次序挪用列表中的拜托。只能歸並雷同類型的拜托。
- 運算符可用於從多播拜托中移除組件拜托。
using System; // Define a custom delegate that has a string parameter and returns void. delegate void CustomDel(string s); class TestClass { // Define two methods that have the same signature as CustomDel. static void Hello(string s) { System.Console.WriteLine(" Hello, {0}!", s); } static void Goodbye(string s) { System.Console.WriteLine(" Goodbye, {0}!", s); } static void Main() { // Declare instances of the custom delegate. CustomDel hiDel, byeDel, multiDel, multiMinusHiDel; // In this example, you can omit the custom delegate if you // want to and use Action<string> instead. //Action<string> hiDel, byeDel, multiDel, multiMinusHiDel; // Create the delegate object hiDel that references the // method Hello. hiDel = Hello; // Create the delegate object byeDel that references the // method Goodbye. byeDel = Goodbye; // The two delegates, hiDel and byeDel, are combined to // form multiDel. multiDel = hiDel + byeDel; // Remove hiDel from the multicast delegate, leaving byeDel, // which calls only the method Goodbye. multiMinusHiDel = multiDel - hiDel; Console.WriteLine("Invoking delegate hiDel:"); hiDel("A"); Console.WriteLine("Invoking delegate byeDel:"); byeDel("B"); Console.WriteLine("Invoking delegate multiDel:"); multiDel("C"); Console.WriteLine("Invoking delegate multiMinusHiDel:"); multiMinusHiDel("D"); } }
輸入:
Invoking delegate hiDel: Hello, A! Invoking delegate byeDel: Goodbye, B! Invoking delegate multiDel: Hello, C! Goodbye, C! Invoking delegate multiMinusHiDel: Goodbye, D!
聲明、實例化和應用拜托
在 C# 1.0 及更高版本中,可以按以下示例所示聲明拜托。
// Declare a delegate. delegate void Del(string str); // Declare a method with the same signature as the delegate. static void Notify(string name) { Console.WriteLine("Notification received for: {0}", name); } // Create an instance of the delegate. Del del1 = new Del(Notify);
C# 2.0 供給了更簡略的辦法來編寫下面的聲明,如以下示例所示。
// C# 2.0 provides a simpler way to declare an instance of Del. Del del2 = Notify;
在 C# 2.0 及更高版本中,還可使用匿名辦法來聲明和初始化拜托,如以下示例所示。
// Instantiate Del by using an anonymous method. Del del3 = delegate(string name) { Console.WriteLine("Notification received for: {0}", name); };
在 C# 3.0 及更高版本中,還可使用 Lambda 表達式來聲明和實例化拜托,如以下示例所示。
// Instantiate Del by using a lambda expression. Del del4 = name => { Console.WriteLine("Notification received for: {0}", name); };
上面的示例闡釋聲明、實例化和應用拜托。 BookDB 類封裝一個書店數據庫,它保護一個書本數據庫。它地下 ProcessPaperbackBooks 辦法,該辦法在數據庫中查找一切平裝書,並對每本平裝書挪用一個拜托。應用的 delegate 類型名為 ProcessBookDelegate。 Test 類應用該類打印平裝書的書名戰爭均價錢。
拜托的應用增進了書店數據庫和客戶代碼之間功效的優越分隔。客戶代碼不曉得書本的存儲方法和書店代碼查找平裝書的方法。書店代碼也不曉得找到平裝書後將對平裝書履行甚麼處置。
// 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); } } }
輸入:
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);
每一個拜托類型都描寫參數的數量和類型,和它可以封裝的辦法的前往值類型。每當須要一組新的參數類型或新的前往值類型時,都必需聲明一個新的拜托類型。
實例化拜托。
聲清楚明了拜托類型後,必需創立拜托對象並使之與特定辦法聯系關系。在上一個示例中,您經由過程按上面示例中的方法將 PrintTitle 辦法傳遞到 ProcessPaperbackBooks 辦法來完成這一點:
bookDB.ProcessPaperbackBooks(PrintTitle);
這將創立與靜態辦法 Test.PrintTitle 聯系關系的新拜托對象。相似地,對象 totaller 的非靜態辦法 AddBookToTotal 是按上面示例中的方法傳遞的:
bookDB.ProcessPaperbackBooks(totaller.AddBookToTotal);
在兩個示例中,都向 ProcessPaperbackBooks 辦法傳遞了一個新的拜托對象。
拜托創立後,它的聯系關系辦法就不克不及更改;拜托對象是弗成變的。
挪用拜托。
創立拜托對象後,平日將拜托對象傳遞給將挪用該拜托的其他代碼。經由過程拜托對象的稱號(前面隨著要傳遞給拜托的參數,括在括號內)挪用拜托對象。上面是拜托挪用的示例:
processBook(b);
與本例一樣,可以經由過程應用 BeginInvoke 和 EndInvoke 辦法同步或異步驟用拜托。