C#之委托

来源:互联网 发布:系统策划 知乎 编辑:程序博客网 时间:2024/06/07 01:10

1:委托是一种数据类型,和类一样。委托是对方法的抽象。把方法当做变量来处理,其作用就是指向一个方法。委托也相当于实现多态,函数可以接受参数,而这里使得参数更加灵活化。相当于c++中函数指针。

namespace 委托{   //define delegate    public delegate void DelegateAdd(int a,int b);}namespace 委托{    class Program    {        static void add1(int a, int b)        {            Console.WriteLine("1");        }        static void add2(int a,int b)        {            Console.WriteLine("2");        }        static void Main(string[] args)        {            //Define a delegate var,because the fuction of "add1" be similar as the define of delegate,            //so we can use it as the function's parameters            DelegateAdd delegate1 = new DelegateAdd(add1);            //DelegateAdd delegate1 = add1;也可以直接这样定义            delegate1 += add2;//Invoking the add1 and add2  together            delegate1(1, 5);//Be similar as “add1(1,5)”            Console.ReadKey();        }    }}

 传递的函数的参数的签名,要和定义的委托参数签名一致。


2:委托事件:对应于客观世界就是钱包,银行可以往你的卡里打钱,或者扣款,但不能使用你的钱包进行购物,只有你自己才可以。

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 委托事件{   public class Dog   {       //事件,其本质就是委托对象,调用执行只能在内部完成=Nature of event is a delegate, when we using it to do something,it must be performed internally.       //也就是一个函数=We can also treat it as a function       //在外部可以使用-= 或者+=       public event Action helloEvent;       public void Sayhello()       {           Console.WriteLine("sd");           helloEvent();                 }   }}using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 委托事件{    class Program    {        public static event Action helloEvent2;//非静态的字段调用要用对象,所以加static         static void Main(string[] args)        {            Dog d1 = new Dog();            //d1.helloEvent()//错误,helloEvent事件不能外部直接调用            d1.helloEvent += helloEvent2;//可以使用+=或者-=            d1.Sayhello();// helloEvent();在内部调用是可以的            Console.ReadKey();        }    }}

但会出现运行时错误,


3:委托实例:在方法中通过传递不同的方法,对另一个参数实现不同的效果。即大写,小写

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 委托{    class Program    {        static string ToUpper(string str)        {            return (str.ToUpper());        }        static string ToLower(string str)        {            return (str.ToLower());        }        static void GoTo(Func<string,string> s1,string str)//s1就相当于一个方法名        {            Console.WriteLine(s1(str));//调用s1函数,需要string参数,并返回string类型的值        }            static void Main(string[] args)        {            GoTo(ToLower, "SWW");            GoTo(ToUpper, "Sopp");            Console.ReadKey();        }    }}

0 0