码迷,mamicode.com
首页 > Windows程序 > 详细

C# 中的委托和事件

时间:2016-12-08 03:22:13      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:bre   ati   好的   tin   []   htm   sum   case   event   

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# 中的委托和事件

标签:bre   ati   好的   tin   []   htm   sum   case   event   

原文地址:http://www.cnblogs.com/nlh774/p/6143392.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!