天天看点

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

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

<p>通过使用 delegate 类,委托实例可以封装属于可调用实体的方法。</p><p>对于实例方法,委托由一个包含类的实例和该实例上的方法组成。</p><p>对于静态方法,可调用实体由一个类和该类上的静态方法组成。</p><p>因此,委托可用于调用任何对象的函数,而且委托是面向对象的、类型安全的。</p><p>定义和使用委托有三个步骤:</p>  

声明

实例化

调用

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

<p><span style="color: #ff00ff;">c#可通过使用委托来确定在运行时选择要调用哪些函数。</span></p>  

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

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

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