合作联系微信: w6668263      合作联系电话:177-9238-7426     

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);
        }
    }

posted on 2012-04-11 16:34  草率的龙果果  阅读(385)  评论(0编辑  收藏  举报

导航