delegate details

来源:互联网 发布:腾讯游戏mac版 编辑:程序博客网 时间:2024/05/01 14:45

The runtime supports reference types called delegates that serve a purpose similar to that of function pointers in C++. In another word, A delegate is a reference type which is similar to function pointer. It can represent both static and instance methods. And delegates are secure, verifiable, and type safe.

 

Since I’ve learnt function pointers, I’d like to express the delegates in the way what I think. By this way, we can define a method whose parameter is also a method, or exactly a method name. This makes expansibility to the code. A delegate looks like a class. In fact, it will be compiled to a class by the compiler. Yep, delegate is a type.

 

using System;

using System.Collections.Generic;

using System.Text;

namespace myDelegate

{

    public delegate void Move(string action);

    class Test

    {

        private static void Bird(string action)

        {

            Console.WriteLine("Bird can " + action);

        }

        private static void Duck(string action)

        {

            Console.WriteLine("Duck can " + action);

        }

        private static void Dog(string action)

        {

            Console.WriteLine("Dog can " + action);

        }

        private static void moveTest(string action, Move Acter)

        {

            Acter(action);

        }

        static void Main(string[] args)

        {

            moveTest("fly", Bird);

            moveTest("swim", Duck);

            moveTest("run", Dog);

            Console.ReadLine();

        }

    }

}

There is another choice. We can avoid using moveTest() and call the methods of Bird(),Duck() and Dog() by delegate.

        

static void Main(string[] args)

        {

            Move m;

            m = Bird;   //eluvate

            m += Duck;  //syntax banding

            m += Dog;   //syntax banding

            m("eat");

            Console.ReadLine();

    } 

    

Pay attention here. The first”=”is for eluvation, and the next”+=”is a syntax of banding. If “+=”takes the place of the first “=”,errors will happen during the compiling time. Is there any way to avoid the danger? Of course,with a little modification, the code will be all right in any case. We code like this:

          

Move n = new Move(Bird);

            n += Duck;

            n("shout");

// or like this:

           Move d = new Move();

             d +=Bird;             //syntax banding here this time

d += Duck;             //banding too

            d("breathe");

 

So a delegate is able to have several values or methods.At last, I’ll talk about the accessibility of the delegates. Usually, we set the attribute of the delegates as private. In this condition,we can easily keep them from been changed by the customer side. Namely, we would better not use public to declare a delegate.