H_J_H

------专用杂物房
posts - 26, comments - 1, trackbacks - 0, articles - 119

[导入]多点委托

Posted on 2006-04-26 21:17 H_J_H 阅读(49) 评论(0)  编辑 收藏 引用
 

多点委托

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

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);

        }

    }

}



sopper 2006-04-13 16:33

文章来源:http://sopper.cnblogs.com/archive/2006/04/13/374398.html
只有注册用户登录后才能发表评论。