C# 委托

在 C# 中,委托是指向方法的指针。这意味着,委托保存着可以被该委托调用的方法的地址。

让我们学习如何定义和执行委托。


定义委托

我们定义一个 delegate,就像定义一个普通方法一样。也就是说,delegate 也有返回类型和参数。例如:

public delegate int myDelegate(int x);

这里,

  • delegate - 关键字
  • int - 委托的返回类型
  • myDelegate - 委托的名称
  • int x - 委托接受的参数

任何可访问类或结构中与委托签名匹配的方法都可以赋值给该委托。

注意: 委托也被称为类型安全指针。


实例化委托

假设我们有一个名为 calculateSum() 的方法,其签名与 myDelegate 相同。

要创建 myDelegate 的一个实例,我们传递一个方法名作为参数。例如:

myDelegate d1 = new myDelegate(calculateSum);

示例:使用委托调用方法

using System;
using System.Collections.Generic;
class Program
{
    // define a method that returns sum of two int numbers 
    static int calculateSum(int x, int y)
    {
        return x + y;
    }

// define a delegate public delegate int myDelegate(int num1, int num2);
static void Main() {
// create an instance of delegate by passing method name myDelegate d = new myDelegate(calculateSum);
// calling calculateSum() using delegate int result = d(5, 6);
Console.WriteLine(result); } }

输出

11

在上面的示例中,我们创建了 myDelegate 的一个实例(d),并将 calculateSum() 作为参数传递。

在这里,我们通过将 56 作为参数值传递给 d 来调用 calculateSum() 方法。


C# 委托的用途

我们可以使用委托来:

  • 提高代码的可重用性并实现灵活性
  • 在触发事件时通知调用哪个方法
  • 定义回调方法

常见问题

C# 中的多播委托

多播委托用于一次指向多个方法。我们使用 += 运算符将方法添加到委托。例如:

using System;
class Program
{
    // method that prints sum of two int numbers 
    public void sum(int x, int y)
    {
        Console.WriteLine("Sum is: " + (x + y));
    }

    // method that prints difference of two int numbers 
    public void difference(int x, int y)
    {
        Console.WriteLine("Difference is: " + (x - y));
    }

    // define a delegate of int type 
    public delegate void myDelegate(int num1, int num2);

    static void Main()
    {
        // instance of Program class
        Program obj = new Program();

        // create an instance of delegate and
        // pass sum method as a parameter 
        myDelegate d = new myDelegate(obj.sum);

// multicast delegate // calls difference() method d += obj.difference;
// pass values to two methods i.e sum() and difference() d(6, 5); } }

输出

Sum is: 11
Difference is: 1
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战