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