C#委托初见

来源:互联网 发布:淘宝网电子商务类型 编辑:程序博客网 时间:2024/05/29 11:21

      委托(Delegate)是C#中一个重要的概念。这次先用一个简单的例子展示一下委托在C#中的用法,先见个面,日后再慢慢熟悉。

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace DelegateApp{    /// <summary>    /// 定义一个委托类型    /// </summary>    /// <param name="x"></param>    /// <returns></returns>    public delegate double DelegateOfPower(double x);    /// <summary>    /// MyMath类中的Power()方法可以被委托变量接收    /// </summary>    class MyMath    {        public double Power(double x)        {            return x * x;        }    }        class Program    {        static void Main(string[] args)        {            MyMath math = new MyMath();            //方法Power被委托接收,也可简写成:DelegateOfPower del = math.Power;            DelegateOfPower del = new DelegateOfPower(math.Power);            System.Console.WriteLine(del(2.2));            System.Console.ReadKey();        }    }}
      从上面的例子可以看出委托可以接收同形参、同返回值的方法,委托接收了这样的方法后就能被当成方法一样去调用。

0 0
原创粉丝点击