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

delegate 可以與具名方法產生關聯。 當您使用具名方法具現化委派時,方法會當做參數傳遞,例如:

// Declare a delegate.
delegate void WorkCallback(int x);

// Define a named method.
void DoWork(int k) { /* ... */ }

// Instantiate the delegate using the method as a parameter.
WorkCallback d = obj.DoWork;

這會使用具名方法呼叫。 使用具名方法建構的委派可封裝靜態方法或執行個體方法。 在舊版 C# 中,要具現化委派只能使用具名方法。 不過,如果建立新方法會產生額外不必要的負荷,C# 可讓您具現化委派,並立即指定呼叫委派時會處理的程式碼區塊。 區塊可包含 Lambda 運算式匿名方法

當做委派參數傳遞的方法必須擁有與委派宣告相同的簽章。 委派執行個體可封裝靜態或執行個體方法。

注意

即使委派可使用 out 參數,但仍不建議您用於多點傳送事件委派,因為無從得知將呼叫哪一個委派。

自 C# 10 起,具有單一多載的方法群組會使用「自然類型」。 這表示編譯器可針對委派類型推斷傳回型別和參數類型:

var read = Console.Read; // Just one overload; Func<int> inferred
var write = Console.Write; // ERROR: Multiple overloads, can't choose

範例

以下是宣告和使用委派的簡單範例。 請注意,委派 Del 和相關聯的方法 MultiplyNumbers 必須擁有相同的簽章

// Declare a delegate
delegate void MultiplyCallback(int i, double j);

class MathClass
{
    static void Main()
    {
        MathClass m = new MathClass();

        // Delegate instantiation using "MultiplyNumbers"
        MultiplyCallback d = m.MultiplyNumbers;

        // Invoke the delegate object.
        Console.WriteLine("Invoking the delegate using 'MultiplyNumbers':");
        for (int i = 1; i <= 5; i++)
        {
            d(i, 2);
        }

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

    // Declare the associated method.
    void MultiplyNumbers(int m, double n)
    {
        Console.Write(m * n + " ");
    }
}
/* Output:
    Invoking the delegate using 'MultiplyNumbers':
    2 4 6 8 10
*/

在下列範例中,一個委派會同時對應到靜態和執行個體方法,並傳回每個方法的特定資訊。

// Declare a delegate
delegate void Callback();

class SampleClass
{
    public void InstanceMethod()
    {
        Console.WriteLine("A message from the instance method.");
    }

    static public void StaticMethod()
    {
        Console.WriteLine("A message from the static method.");
    }
}

class TestSampleClass
{
    static void Main()
    {
        var sc = new SampleClass();

        // Map the delegate to the instance method:
        Callback d = sc.InstanceMethod;
        d();

        // Map to the static method:
        d = SampleClass.StaticMethod;
        d();
    }
}
/* Output:
    A message from the instance method.
    A message from the static method.
*/

另請參閱