如何声明、实例化和使用委托(C# 编程指南)

保存
 
 

 


 

如何声明、实例化和使用委托(C# 编程指南)

本文内容

  1. 示例
  2. 可靠编程
  3. 另请参阅

可以使用以下任一方法声明委托:

  • 使用匹配签名声明委托类型并声明方法:
C#
// Declare a delegate.
delegate void NotifyCallback(string str);

// Declare a method with the same signature as the delegate.
static void Notify(string name)
{
    Console.WriteLine($"Notification received for: {name}");
}
C#
// Create an instance of the delegate.
NotifyCallback del1 = new NotifyCallback(Notify);
  • 将方法组分配给委托类型:
C#
// C# 2.0 provides a simpler way to declare an instance of NotifyCallback.
NotifyCallback del2 = Notify;
  • 声明匿名方法:
C#
// Instantiate NotifyCallback by using an anonymous method.
NotifyCallback del3 = delegate(string name)
    { Console.WriteLine($"Notification received for: {name}"); };
  • 使用 lambda 表达式:
C#
// Instantiate NotifyCallback by using a lambda expression.
NotifyCallback del4 = name =>  { Console.WriteLine($"Notification received for: {name}"); };

有关详细信息,请参阅 Lambda 表达式

下面的示例演示如何声明、实例化和使用委托。 BookDB 类封装用来维护书籍数据库的书店数据库。 它公开一个方法 ProcessPaperbackBooks,用于在数据库中查找所有平装书并为每本书调用委托。 使用的 delegate 类型名为 ProcessBookCallback。 Test 类使用此类打印平装书的书名和平均价格。

使用委托提升书店数据库和客户端代码之间的良好分隔功能。 客户端代码程序不知道如何存储书籍或书店代码如何查找平装书。 书店代码不知道它在找到平装书之后对其执行什么处理。

示例

C#
// 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 ProcessBookCallback(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(ProcessBookCallback 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($"   {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(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);

            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
*/

可靠编程

  • 声明委托。

    以下语句声明新的委托类型。

    C#
    public delegate void ProcessBookCallback(Book book);
    

    每个委托类型描述自变量的数量和类型,以及它可以封装的方法的返回值类型。 每当需要一组新的自变量类型或返回值类型,则必须声明一个新的委托类型。

  • 实例化委托。

    声明委托类型后,则必须创建委托对象并将其与特定的方法相关联。 在上例中,你通过将 PrintTitle 方法传递给 ProcessPaperbackBooks 方法执行此操作,如下面的示例所示:

    C#
    bookDB.ProcessPaperbackBooks(PrintTitle);
    

    这将创建一个新的与静态方法 Test.PrintTitle 关联的委托对象。 同样,如下面的示例所示,传递对象 totaller 中的非静态方法 AddBookToTotal

    C#
    bookDB.ProcessPaperbackBooks(totaller.AddBookToTotal);
    

    在这两种情况下,都将新的委托对象传递给 ProcessPaperbackBooks 方法。

    创建委托后,它与之关联的方法就永远不会更改;委托对象是不可变的。

  • 调用委托。

    创建委托对象后,通常会将委托对象传递给将调用该委托的其他代码。 委托对象是通过使用委托对象的名称调用的,后跟用圆括号括起来的将传递给委托的自变量。 下面是一个委托调用示例:

    C#
    processBook(b);
    

    委托可以同步调用(如在本例中)或通过使用 BeginInvoke 和 EndInvoke 方法异步调用。

posted on   漫思  阅读(7)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
历史上的今天:
2023-12-27 Facade 外观模式简介与 C# 示例【结构型5】【设计模式来了_10】
2023-12-27 Builder 生成器模式简介与 C# 示例【创建型2】【设计模式来了_2】
2023-12-27 Composite 组合模式简介与 C# 示例【结构型3】【设计模式来了_8】
2023-12-27 C# 中关于 T 泛型【C# 基础】
2023-12-27 C# 9.0 添加和增强的功能【基础篇】
2023-12-27 C# Replace:一个熟悉而又陌生的替换
2023-12-27 Decorator 装饰者模式简介与 C# 示例【结构型4】【设计模式来了_9】

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8
点击右上角即可分享
微信分享提示