天天看點

C# Delegate 使用

Delegate, Event

Delegate其實就相當于C++/C裡面的函數指針.用法如下:

1.最正常的使用

    class Program

    {

        public delegate void NumberChangedEventHandler(int number);

        class Publisher

        {

            public NumberChangedEventHandler NumberChanged;  

        }

        class Subscriber

        {

            public void OnNumberChanged(int number)

            {

                string message = "New value is " + number;

                Console.WriteLine(message);

            }

        }

        static void Main(string[] args)

        {

            Publisher pub = new Publisher();

            Subscriber sub1 = new Subscriber();

            Subscriber sub2 = new Subscriber();

            pub.NumberChanged += new NumberChangedEventHandler(sub1.OnNumberChanged);

            pub.NumberChanged += new NumberChangedEventHandler(sub2.OnNumberChanged);

            pub.NumberChanged(3);

            Console.WriteLine("over");

        }

    }

2.直接當成函數指針用

    class Program

    {

        public delegate void NumberChangedEventHandler(int number);

        class Publisher

        {

            public NumberChangedEventHandler NumberChanged;  

        }

        class Subscriber

        {

            public void OnNumberChanged(int number)

            {

                string message = "New value is " + number;

                Console.WriteLine(message);

            }

        }

        static void Main(string[] args)

        {

            Publisher pub = new Publisher();

            Subscriber sub1 = new Subscriber();

            pub.NumberChanged = sub1.OnNumberChanged;

            pub.NumberChanged(3);

        }

    }

3.異步調用

    class Program

    {

        public delegate void NumberChangedEventHandler(int number);

        class Publisher

        {

            public NumberChangedEventHandler NumberChanged;  

        }

        class Subscriber

        {

            public void OnNumberChanged(int number)

            {

                string message = "New value is " + number;

                Console.WriteLine(message);

            }

        }

        static void Main(string[] args)

        {

            Publisher pub = new Publisher();

            Subscriber sub1 = new Subscriber();

            pub.NumberChanged += new NumberChangedEventHandler(sub1.OnNumberChanged);

            pub.NumberChanged.BeginInvoke(3, null, null);

        }

    }

以上所述為怎麼樣,但如何用好,即将這個機制用在什麼Context中,确又是另一門學問

Event就是delegate的一個具體應用,但是它的應用是比較簡單的,隻是加上了限制:此delegate(即event)隻能在本類中調用