委托的创建、实例化和调用

通过使用 Delegate 类,委托实例可以封装属于可调用实体的方法。

对于实例方法,委托由一个包含类的实例和该实例上的方法组成。

对于静态方法,可调用实体由一个类和该类上的静态方法组成。

因此,委托可用于调用任何对象的函数,而且委托是面向对象的、类型安全的。

定义和使用委托有三个步骤:

  • 声明

  • 实例化

  • 调用


C#可通过使用委托来确定在运行时选择要调用哪些函数。

以下代码演示了委托的创建、实例化和调用:

C#  复制代码 
public class MathClass
{
    public static long Add(int i, int j)       // static
    {
        return (i + j);
    }

    public static long Multiply (int i, int j)  // static
    {
        return (i * j);
    }
}

class TestMathClass
{
    delegate long Del(int i, int j);  // declare the delegate type

    static void Main()
    {
        Del operation;  // declare the delegate variable

        operation = MathClass.Add;       // set the delegate to refer to the Add method
        long sum = operation(11, 22);             // use the delegate to call the Add method

        operation = MathClass.Multiply;  // change the delegate to refer to the Multiply method
        long product = operation(30, 40);         // use the delegate to call the Multiply method

        System.Console.WriteLine("11 + 22 = " + sum);
        System.Console.WriteLine("30 * 40 = " + product);
    }
}


 

输出
11 + 22 = 33 

30 * 40 = 1200 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值