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

在这里插入图片描述

发布了201 篇原创文章 · 获赞 210 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_40666620/article/details/104910361