委托

把方法参数化能够把方法作为参数传进函数也称为代理,事件也是一种委托;

定义在类的最外面

 

关键字:delegate

函数签名:签名和函数保持一致

定义委托的时候要根据函数来定义

public delegate int First(int a,int b);

指向的方法的返回类型,需要参数必须一致!

 

2、定义委托变量,指向方法

 

委托不能被实例化,因为不是类;

 

First f = new JiaFa().JiaFa; //新建委托变量,指向方法,注意!!方法不需要小括号!!

 

第二次可以使用+=

 

public int JiaFa(int a,int b)

{

       return a+b;

}

 

调用:

f(5,3);

 

可以理解为函数的指针,委托指向哪个函数,则这个委托就代表哪个函数

可以让函数当做参数一样进行传递

 

例:

    //定义委托

    public delegate void SuiBian(string s);

 

    class Program

    {

        static void Main(string[] args)

        {

           // Test t1 = new Test();

           //Test t2 = new Test();

 

            //DBDA db = DBDA.DuiXiang();

            //db.host = "localhost";

            //DBDA db1 = DBDA.DuiXiang();

 

 

            //委托

            //把方法参数化

            SuiBian s = China;

 

            s += America; //+=是绑定方法  -=去掉一个方法

 

            //事件

            //事件就是一种特殊的委托

 

 

            //调用语音方法

            Speak(s);

 

          

 

            Console.WriteLine();

            Console.ReadLine();

 

        }

 

        //语音功能的方法

        static void Speak(SuiBian yu)

        {

            yu("张三");

 

            //if (n == 0)

            //{

            //    America();

            //}

            //else if (n == 1)

            //{

            //    China();

            //}

            //else if (n == 2)

            //{

            //    HanYu();

            //}

   

        }

 

        //语音包

        public static void America(string s)

        {

            Console.WriteLine(s+"hello");

        }

        static void China(string s)

        {

            Console.WriteLine(s+"你好");

        }

        static void HanYu(string s)

        {

            Console.WriteLine(s+"bjdkaj");

        }

 

 

    }

posted on 2016-08-12 14:24  Lovetolaugh  阅读(620)  评论(0编辑  收藏  举报