天天看点

Delegate two

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

//使用委托方式之一:把方法组合到一个数组中,再循环中调用不同的方法

namespace Delegate

{

    delegate double DoubleOp(double x);//一旦定义了委托类,就可以实例化它的实例,像处理一般的类那样

    class Program

    {

        static void Main(string[] args)

        {        

            DoubleOp[] opertions = {new DoubleOp(MathsOperations.MultiplyByTwo),//每一个元素都初始化为由MathOperations 类执行的不同操作(封装方法)

             new DoubleOp(MathsOperations.Square)

             };

            for (int i = 0; i < opertions.Length; i++)

            {

                Console.WriteLine("Using operations[{0}]:",i);

                ProcessAndDisplayNumber(opertions[i], 2.0);//将委托传递给ProcessAndNumber() 方法,仅传递委托名,但不带任何参数

                ProcessAndDisplayNumber(opertions[i], 7.94);//operation[i]表示“这个委托”,也即;委托代表的方法

                ProcessAndDisplayNumber(opertions[i], 1.414);//operation[i](2.0)  表示“调用这个方法,参数放在括号中”

                Console.ReadLine();

            }

        }

        /// <summary>

        /// 把一个委托作为其第一个参数

        /// </summary>

        /// <param name="action"></param>

        /// <param name="value"></param>

        static void ProcessAndDisplayNumber(DoubleOp action,double value)

        {

            double result = action(value);//调用action委托实例封装的方法,其返回结果存储在result 中

            Console.WriteLine("Value is{0},result of operation is {1}",value ,result );         

    }

    /// <summary>

    /// 委托要调用的两个方法

    /// </summary>

    class MathsOperations

        public static double MultiplyByTwo(double value)

            return value * 2;       

        public static double Square(double value)

            return value * value;

    }   

}

继续阅读