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

 

转载于:https://www.cnblogs.com/gylhaut/p/5785572.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值