委派 & 事件 Example

  • 936
  • 0
  • C#
  • 2012-10-23

摘要:委派 & 事件 Example


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public delegate void DoGreeting(string name);

    public class ManagerHello
    {
        public event DoGreeting MakeGreet;

        public void GreetHello(string name)
        {
            MakeGreet(name);
        }
    }
    class Program
    {
        static void EnglishGreeting(string name)
        {
            Console.WriteLine("Hello, " + name);
        }

        static void ChineseGreeting(string name)
        {
            Console.WriteLine("你好, " + name);
        }

        static void Main(string[] args)
        {
            ManagerHello manager = new ManagerHello();
            manager.MakeGreet += EnglishGreeting;
            manager.MakeGreet += ChineseGreeting;
            manager.GreetHello("周星星");

            manager.MakeGreet -= EnglishGreeting;
            manager.GreetHello("周星星");
        }
    }
}