delegate (C# 參考)

委派型別的宣告與方法簽章類似。 它有傳回值和任何型別的任何參數數目:

public delegate void TestDelegate(string message);
public delegate int TestDelegate(MyType m, long num);

delegate 是可用來封裝具名方法或匿名方法的參考型別。 委派大致類似 C++ 的函式指標,但是,委派型別安全 (Type-Safe) 又具有安全性。 如需委派的應用程式,請參閱委派泛型委派

備註

委派是事件的基礎。

將委派與具名方法或匿名方法建立關聯,即可具現化 (Instantiated) 委派。 如需詳細資訊,請參閱具名方法匿名方法

委派必須以具有相容傳回型別和輸入參數的方法或 Lambda 運算式具現化。 如需方法簽章中可允許之變異數等級的詳細資訊,請參閱委派中的變異數 (C# 和 Visual Basic)。 若要搭配匿名方法使用,就要同時宣告委派以及其相關聯的程式碼。 委派的這兩種具現化方法都將在此章節中討論。

範例

// Declare delegate -- defines required signature:
delegate double MathAction(double num);

class DelegateTest
{
    // Regular method that matches signature:
    static double Double(double input)
    {
        return input * 2;
    }

    static void Main()
    {
        // Instantiate delegate with named method:
        MathAction ma = Double;

        // Invoke delegate ma:
        double multByTwo = ma(4.5);
        Console.WriteLine(multByTwo);

        // Instantiate delegate with anonymous method:
        MathAction ma2 = delegate(double input)
        {
            return input * input;
        };

        double square = ma2(5);
        Console.WriteLine(square);

        // Instantiate delegate with lambda expression
        MathAction ma3 = s => s * s * s;
        double cube = ma3(4.375);

        Console.WriteLine(cube);
    }
}

C# 語言規格

如需詳細資訊,請參閱 C# 語言規格。 語言規格是 C# 語法和用法的決定性來源。

請參閱

參考

C# 關鍵字

參考型別 (C# 參考)

委派 (C# 程式設計手冊)

事件 (C# 程式設計手冊)

使用具名和匿名方法委派的比較 (C# 程式設計手冊)

匿名方法 (C# 程式設計手冊)

概念

C# 程式設計手冊

其他資源

C# 參考