点点滴滴访问量:
 

多点委托

前面使用的委托只代表一个方法,下面来看看多点委托,就是一个委托代表多个方法,调用多点委托时,所代表的所有方法将按顺序依次调用。

MyDelegate d1 = new MyDelegate(MyClass.Square);

MyDelegate d2 = new MyDelegate(MyClass.Cube);

MyDelegate d3 = new MyDelegate(MyClass.Double);

MyDelegate d = d1 + d2 +d3;

 和下面Main方法里的那段等效

例:

using System;

 

namespace duodianweituo

{

    class Class1

    {

        [STAThread]

        static void Main(string[] args)

        {

            MyDelegate d = new MyDelegate(MyClass.Square);

            d += new MyDelegate(MyClass.Cube);

            d += new MyDelegate(MyClass.Double);

            ExecuteMethod(d,2);

        }

 

        static void ExecuteMethod(MyDelegate d, float x)

        {

            d(x);

        }

    }

    delegate void MyDelegate(float x);

   

    class MyClass

    {

        public static void Square(float x)

        {

            float result = x * x;

            Console.WriteLine("{0}的平方等于:{1}",x,result);

        }

 

        public static void Cube(float x)

        {

            float result = x * x * x;

            Console.WriteLine("{0}的立方等于:{1}",x , result);

        }

 

        public static void Double(float x)

        {

            float result = 2 * x;

            Console.WriteLine("{0}的倍数等于:{1}",x , result);

        }

    }

}

posted on 2006-04-13 16:33  sopper  阅读(316)  评论(0编辑  收藏  举报