C#簡單理解回調函數,用action簡單實現

其實理解回調函數真的很簡單
我們只需要這樣理解
需要傳遞進去一個參數,這個參數是一個方法,並且可以調用
我們只需要幾步

  1. 聲明一個方法,這個方法需要傳遞進去一個函數,並且這個傳遞進去的函數也是需要參數的,我們把它聲明爲Action<paramsType’>'中的paramsType,如下
//看吧,我們把函數當參數傳遞進去了,就是Action,這個函數所需要的參數類型就是<>中的string
 static void SomeMethod_Just_Process_And_Need_OtherFunc_NamedAction(string name ,Action<string>action)
 {
     name = "hello world , your name is " + name;
     action(name);
 }
  1. 我們去聲明這個需要被當參數傳遞進去的方法,並且所需的參數也是規定好的,如下
static void the_method_which_is_named_action(string theProcessedStr)
{
    Console.WriteLine(theProcessedStr);
}
  1. 調用即可,如下
static void Main(string[] args)
{
	   SomeMethod_Just_Process_And_Need_OtherFunc_NamedAction("william_x_f_wang", the_method_which_is_named_action);
	   Console.ReadLine();
}

完整代碼如下

using System;

namespace TCP客戶端
{
    class Program
    {

		// 看看方法名字也知道,我們定義一個方法,這個方法並沒有把事情做完
		// 它需要其他的方法來處理下面的數據
		// 那麼Action<type> name 中的type就是那個方法所需要的參數類型
        static void SomeMethod_Just_Process_And_Need_OtherFunc_NamedAction(string name ,Action<string>action)
        {
            name = "hello world , your name is " + name;
            action(name);
        }
		
		//看名字,這個就是那個需要被回調的函數
		static void the_method_which_is_named_action(string theProcessedStr)
        {
            Console.WriteLine(theProcessedStr);
        }

        static void Main(string[] args)
        {
        //在Mian中,直接調用方法,然後把回調的函數傳遞進去
            SomeMethod_Just_Process_And_Need_OtherFunc_NamedAction("william_x_f_wang", the_method_which_is_named_action);
            Console.ReadLine();
    }
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章