C#中的委托

using System;
using System.Collections;

namespace ConsoleApplication1
{
 /// <summary>
 /// DelegateEvent 的摘要说明。
 /// </summary>
 class DBConnection
 {
  protected static int NextConnectionNbr = 1;
  protected string connectionName;
  public string ConnectionName
  {
   get
   {
    return connectionName;
   }
  }
  public DBConnection()
  {
   connectionName = "Database Connection" + DBConnection.NextConnectionNbr++;
  }
 }
 class DBManager
 {
  protected ArrayList activeConnections;
  public DBManager()
  {
   activeConnections  = new ArrayList();
   for(int i = 0; i < 5; i++)
   {
    this.activeConnections.Add(new DBConnection());
   }
  }
  public delegate void EnumConnectionsCallback(DBConnection connection);
  public void EnumConnections(EnumConnectionsCallback callback)
  {
   foreach(DBConnection connection in activeConnections)
   {
    callback(connection);
   }
  }
  
 }
 
 public class DelegateEvent
 {
  //与把委托定义为静态方法一起使用
  static DBManager.EnumConnectionsCallback printConnections = new ConsoleApplication1.DBManager.EnumConnectionsCallback(PrintConnections);
  //定义一个委托接收者的方法
   static void PrintConnections(DBConnection connection)
  {
   Console.WriteLine("[InstanceDelegate].PrintConnections{0}",connection.ConnectionName);
  }
  //委托的一般实例
  public static void InstanceDelegate()
  {
   DBManager dbManager = new DBManager();
   Console.WriteLine("[Main] Instantiating the" + "delegate method");
   DBManager.EnumConnectionsCallback printConnections = new ConsoleApplication1.DBManager.EnumConnectionsCallback(DelegateEvent.PrintConnections);
   Console.WriteLine("[Mani] Calling EnumConnections" + "-passing the delegate");
   dbManager.EnumConnections(printConnections);
   Console.ReadLine();
  }
  //把委托定义为静态成员
  public static void StaticDelegate()
  {
   DBManager dbManager = new DBManager();
   Console.WriteLine("[Mani] Calling EnumConnections" + "-passing the delegate");
   dbManager.EnumConnections(printConnections);
   Console.ReadLine();
  }
  //在需要时创建委托,定义一个获取方法特性
   DBManager.EnumConnectionsCallback PrintConnectionsProperty
  {
   get
   {
    return new  DBManager.EnumConnectionsCallback(PrintConnections);
   }
  }
  //委托属性
  public static void DelegateProperty()
  {
   DelegateEvent app = new DelegateEvent();
   DBManager dbManager = new DBManager();
   Console.WriteLine("[Main] Calling EnumConnections - " + "passing the delegate");
   dbManager.EnumConnections(app.PrintConnectionsProperty);

  }
  public static void Main()
  {
//   InstanceDelegate();
//   StaticDelegate();
   DelegateProperty();

  }
 }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值