首页 > 代码库 > C# 中的委托和事件

C# 中的委托和事件

C# 中的委托和事件

http://www.tracefact.net/CSharp-Programming/Delegates-and-Events-in-CSharp.aspx

    /// <summary>
    /// 不好的设计
    /// 后期增加语种需要增加改动3个地方:语种枚举、switch-case、方法
    /// </summary>
    public class BadDesign
    {
        public enum Language
        {
            English, 
            Chinese
            //add other language
        }

        public void GreetPeople(string name, Language lang)
        {
            switch (lang)
            {
                case Language.English:
                    EnglishGreeting(name);
                    break;
                case Language.Chinese:
                    ChineseGreeting(name);
                    break;
                //add other language
            }
        }

        public void EnglishGreeting(string name)
        {
            Console.WriteLine("Good Morning, " + name);
        }

        public void ChineseGreeting(string name)
        {
            Console.WriteLine("早上好, " + name);
        }

        //add language method
    }


 /// <summary>
    /// 相对较好的设计
    /// 后期增加语种需要增加改动1个地方:语种方法
    /// </summary>
    class GoodDesign_Delegate
    {
        public void GreetPeople(string name, GreetingDelegate MakeGreeting)
        {
            MakeGreeting(name);
        }

        public void EnglishGreeting(string name)
        {
            Console.WriteLine("Good Morning, " + name);
        }

        public void ChineseGreeting(string name)
        {
            Console.WriteLine("早上好, " + name);
        }

        //add language method
    }


public delegate void GreetingDelegate(string name);


   class Program
    {
        static void Main(string[] args)
        {
            new BadDesign().GreetPeople("nlh", Delegate_Event.BadDesign.Language.Chinese);
            new BadDesign().GreetPeople("nlh", Delegate_Event.BadDesign.Language.English);

            new GoodDesign_Delegate().GreetPeople("nlh", new GoodDesign_Delegate().ChineseGreeting);
            new GoodDesign_Delegate().GreetPeople("nlh", new GoodDesign_Delegate().EnglishGreeting);
            Console.Read();
        }
    }

 

C# 中的委托和事件