1. 程式人生 > >委托(作用:解耦)

委托(作用:解耦)

AR 輸入 實例 wrong console nbsp sum tasks with

1.了解委托

  MyDelegate類代碼如下:

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

namespace MyDelegate
{
    /// <summary>
    /// 委托可以定義在類外面
    /// </summary>
    public delegate void OutNoReturnNoPara();
    public delegate void OutNoReturnWithPara(int
x, int y); class DelegateClass { /// <summary> /// 1.聲明委托,委托的參數與函數的參數必須一致 /// </summary> public delegate void NoReturnNoPara(); public delegate void NoReturnWithPara(int x, int y); public delegate string NoPara(); public delegate DateTime WithPara(string
name,int size); public static void Show()//靜態方法的委托只能調用靜態方法 { //2.實例化委托,這裏的method實例化後就是一個Plus函數 NoReturnWithPara method = new NoReturnWithPara(Plus);//等價於NoReturnWithPara method = Plus; //3.調用委托 method.Invoke(3, 4);//等價於method(3, 4); method.BeginInvoke(4
, 5,null,null);//補充:新建一個線程,異步調用 } public static void Plus(int x,int y) { Console.WriteLine("這裏是Plus x={0} y={1}", x, y); } } }

  在Program使用DelegateClass.Show();

  可以調用Plus這個方法

2.委托的用處

  1)打招呼===》普通方法

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

namespace MyDelegate
{
    class GreetingClass
    {public static void Greeting(string name,PeopleType type)//輸入和誰打招呼,和這個人是哪個國家的人
        {
            if(type==PeopleType.Chinese)
            {
                Console.WriteLine("{0}早上好", name);
            }
            else if(type==PeopleType.English)
            {
                Console.WriteLine("{0}Morning", name);
            }
            else
            {
                throw new Exception("wrong PeopleType");
            }
        }
    }public enum PeopleType //枚舉,定義國家
    {
        Chinese,English
    }
}

  在Program使用GreetingClass.Greeting("kxy",PeopleType.Chinese);//kxy是一個中國人,所以使用PeopleType.Chinese

可以實現給不同國家的人打招呼用對應國家的語言

  但是如果我們需要增加一種語言,則需要修改枚舉PeopleType和函數Greeting

  2)打招呼===》委托方法

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

namespace MyDelegate
{
    class GreetingClass
    {

        public static void GreetingChinese(string name)
        {
            Console.WriteLine("{0}早上好", name);
        }
        public static void GreetingEnglish(string name)
        {
            Console.WriteLine("{0}Morning", name);
        }
    }
    public delegate void GreetingHandler(string name);
}

  Program代碼如下:

 GreetingHandler handle = new GreetingHandler(GreetingClass.GreetingEnglish);//指明是哪國人
 handle("flt");//輸入人的名字

  當需要增加一種新的語言時,直接增加一個Greeting*******函數就可以了,解除耦合

委托(作用:解耦)