zoukankan      html  css  js  c++  java
  • Net中委托之三委托的高级应用

    1. 使用委托来解决逻辑分离,解除耦合

    2.委托的高级应用实例

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace MyDelegateDemo
    {
        public delegate void SayHelloHandler(string name);//1.委托的声明
        public class Greeting
        {
            public static void SayHello(string name, PeopleType type)
            {
                if (type == PeopleType.Chinese)
                {
                    Console.WriteLine("早上好,{0}", name);
                }
                else if (type == PeopleType.American)
                {
                    Console.WriteLine("Good morning,{0}", name);
                }
            }
            /// <summary>
            /// 委托,逻辑分离,解除耦合
            /// </summary>
            /// <param name="name"></param>
            /// <param name="sayHello">委托的实例</param>
            public static void SayHelloDelegate(string name, SayHelloHandler sayHello)
            {
                sayHello(name);//委托的调用
            }
            public static void SayHelloChinese(string name)
            {
                Console.WriteLine("早上好,{0}", name);
            }
            public static void SayHelloAmerican(string name)
            {
                Console.WriteLine("Good morning,{0}", name);
            }
        }
        public enum PeopleType
        {
            Chinese,
            American
        }
    }
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace MyDelegateDemo
    {
        class Program
        {
            
            //采用委托易于扩展,对扩展开放,对修改封闭的原则
            static void Main(string[] args)
            {
                Console.WriteLine("欢迎来到流星小子博客学习");
                Greeting.SayHello("流星小子", PeopleType.Chinese);
                Greeting.SayHello("Meter", PeopleType.American);
                //委托的实例化
                SayHelloHandler sayHelloHandler = new SayHelloHandler(Greeting.SayHelloChinese);
                Greeting.SayHelloDelegate("流星小子", sayHelloHandler);
    
                SayHelloHandler sayHello = new SayHelloHandler(Greeting.SayHelloAmerican);
                Greeting.SayHelloDelegate("Meter", sayHello);
                //sayHelloHandler -= Greeting.SayHelloChinese;
                //sayHelloHandler += Greeting.SayHelloAmerican;
                //Greeting.SayHelloDelegate("MeterName", sayHelloHandler);
                //sayHelloHandler -= Greeting.SayHelloAmerican;
                Console.Read();
            }
        }
    }
  • 相关阅读:
    IOS开发中实现UITableView按照首字母将集合进行检索分组
    IOS开发中设置导航栏主题
    IOS中使用.xib文件封装一个自定义View
    IOS中将字典转成模型对象
    WindowsPhone8中LongListSelector的扩展解决其不能绑定SelectdeItem的问题
    WindowsPhone8.1 开发-- 二维码扫描
    tomcat 开机自启
    redis ubuntu 开机自启
    webStorm 中使用 supervisor 调试
    ubuntu 14.04 tab失效问题
  • 原文地址:https://www.cnblogs.com/gylhaut/p/5785572.html
Copyright © 2011-2022 走看看