• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号
您的位置:首页 > 程序设计 >C#教程 > 举例讲解C#编程中委托的实例化使用

举例讲解C#编程中委托的实例化使用

作者: 字体:[增加 减小] 来源:互联网 时间:2017-05-28

通过本文主要向大家介绍了c语言程序举例,c语言举例,c语言函数举例,c语言循环结构举例,出口退税举例等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

合并委托
本示例演示如何创建多播委托。 委托对象的一个有用属性是:可以使用 + 运算符将多个对象分配给一个委托实例。多播委托包含已分配委托的列表。在调用多播委托时,它会按顺序调用列表中的委托。只能合并相同类型的委托。
- 运算符可用于从多播委托中移除组件委托。

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");
  }
}

</div>

输出:

Invoking delegate hiDel:
 Hello, A!
Invoking delegate byeDel:
 Goodbye, B!
Invoking delegate multiDel:
 Hello, C!
 Goodbye, C!
Invoking delegate multiMinusHiDel:
 Goodbye, D!
</div>


声明、实例化和使用委托
在 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);

</div>

C# 2.0 提供了更简单的方法来编写上面的声明,如以下示例所示。

// C# 2.0 provides a simpler way to declare an instance of Del.
Del del2 = Notify;
</div>

在 C# 2.0 及更高版本中,还可以使用匿名方法来声明和初始化委托,如以下示例所示。

// Instantiate Del by using an anonymous method.
Del del3 = delegate(string name)
  { Console.WriteLine("Notification received for: {0}", name); };
</div>

在 C# 3.0 及更高版本中,还可以使用 Lambda 表达式来声明和实例化委托,如以下示例所示。

// Instantiate Del by using a lambda expression.
Del del4 = name => { Console.WriteLine("Notification received for: {0}", name); };
</div>

下面的示例阐释声明、实例化和使用委托。 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);
    }
  }
}

</div>

输出:

Paperback Book Titles:
  The C Programming Language
  The Unicode Standard 2.0
  Dogbert's Clues for the Clueless
Average Paperback Book Price: $23.97
</div>

可靠编程
声明委托。
下面的语句声明一个新的委托类型。

public delegate void ProcessBookDelegate(Book book);
</div>
分享到:QQ空间新浪微博腾讯微博微信百度贴吧QQ好友复制网址打印

您可能想查找下面的文章:

  • 举例讲解C#编程中对设计模式中的单例模式的运用
  • 举例讲解C#编程中委托的实例化使用
  • 举例讲解C#中自动实现的属性

相关文章

  • 2017-05-28C#查找素数实现方法
  • 2017-05-28c#中xml文档注释编译dll引用到其它项目示例
  • 2017-05-28C#处理datagridview虚拟模式的方法
  • 2017-05-28字符串转换成枚举类型的方法
  • 2017-05-28C#网络编程基础之进程和线程详解
  • 2017-05-28C# 字符串处理小工具
  • 2017-05-2810个C#程序员经常用到的实用代码片段
  • 2017-05-28C#实现的调用DOS命令操作类实例
  • 2017-05-28WinForm中comboBox控件数据绑定实现方法
  • 2017-05-28C#中Ilist与list的区别小结

文章分类

  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号

最近更新的内容

    • c#解压文件的实例方法
    • 给c#添加SetTimeout和SetInterval函数
    • C#中Params的用法
    • C#把数组中的某个元素取出来放到第一个位置的实现方法
    • C# 分支与循环介绍
    • C#中struct和class的区别详解
    • DataAdapter.Fill指定条数记录,数据库返回全部记录还是返回所指定的记录条数?
    • C#中Arraylist的sort函数用法实例分析
    • c# 如何将RadioButton与DataTable数据进行绑定
    • 使用HttpHanlder处理404:File not found的问题

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有