C#中的委托

来源:互联网 发布:qq网络音乐地址mp3 编辑:程序博客网 时间:2024/06/06 00:27

委托(delegate)是C#的一种比较特殊但是又很重要的类型,他的作用是存储函数引用,需要用到关键词delegate。

需要注意一点是,当存储函数引用时,delegate与待存储的函数的返回值与参数列表要一致,名称没有做规定。

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication1{    class Program    {        delegate void Print(int n);        static void PrintA(int n)        {            Console.WriteLine("A--->"+n);        }        static void PrintB(int n)        {            Console.WriteLine("B--->" + n);        }        static void Main(string[] args)        {            Print p;            p = new Print(PrintA);            p(2);            p = new Print(PrintB);            p(2);            Console.ReadKey();        }    }}

上面会输出A---->2,然后输出B---->2.

在上面的实例中,p就是委托,它存储了PrintA和PrintB函数。比如在p = new Print(PrintA)中p存储了PrintA函数的引用,当p(2)时实际调用的是PrintA函数。

委托的用法比较特殊,记住就行了。

0 0