Because it's kind of clunky that the client has to instantiate the delegate each time the delegate is to be used, C# allows you to define as a static class member the method that will be used in the creation of the delegate. Following is the example from the previous section, changed to use that format. Note that the delegate is now defined as a static member of the class named myCallback, and also note that this member can be used in the Main method without the need for the client to instantiate the delegate.
客户代码在委托每次被使用时都要实例化,由于这种冗余,C#允许你像一个静态类成员一样定义在委托创建中要使用的方法。下面的例子来自前面的部分,并改变了使用形式。
需要注意的是这个委托现在被定义成了静态类成员,命名为myCallback,还需要注意的是这个类成员能用于Main方法,而且不需要在客户端实例化该委托。
using System;
class DBConnection
{
public DBConnection(string name)
{
this.name = name;
}
protected string Name;
public string name
{
get
{
return this.Name;
}
set
{
this.Name = value;
}
}
}
class DBManager
{
static DBConnection[] activeConnections;
public void AddConnections()
{
activeConnections = new DBConnection[5];
for (int i = 0; i < 5; i++)
{
activeConnections[i] = new
DBConnection("DBConnection " + (i + 1));
}
}
public delegate void EnumConnectionsCallback(DBConnection connection);
public static void EnumConnections(EnumConnectionsCallback callback)
{
foreach (DBConnection connection in activeConnections)
{
callback(connection);
}
}
}
class Delegate2App
{
public static DBManager.EnumConnectionsCallback myCallback =
new DBManager.EnumConnectionsCallback(ActiveConnectionsCallback);
public static void ActiveConnectionsCallback(DBConnection connection)
{
Console.WriteLine ("Callback method called for " +
connection.name);
}
public static void Main()
{
DBManager dbMgr = new DBManager();
dbMgr.AddConnections();
DBManager.EnumConnections(myCallback);
}
}
NOTE
Because the standard naming convention for delegates is to append the word Callback to the method that takes the delegate as its argument, it's easy to mistakenly use the method name instead of the delegate name. In that case, you'll get a somewhat misleading compile-time error that states that you've denoted a method where a class was expected. If you get this error, remember that the actual problem is that you've specified a method instead of a delegate.
注意
委托标准的命名风格是附加单词Callback到要使用该委托作为参数的方法。而人们常常错误的用这个方法的名字代替委托的名字。如果是那样的话,你将得到一些令人费解的编译时错误,这个错误说你已经在类中表示了这个方法。如果你得到了这个错误,记得问题是在于你指定了一个方法作为委托。