天天看點

《C#内幕》(PartⅢ—14—2) 中英對照之——定義委托為靜态成員

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到要使用該委托作為參數的方法。而人們常常錯誤的用這個方法的名字代替委托的名字。如果是那樣的話,你将得到一些令人費解的編譯時錯誤,這個錯誤說你已經在類中表示了這個方法。如果你得到了這個錯誤,記得問題是在于你指定了一個方法作為委托。