C#简单实现回调函数
方式一
//C# 简单实现回调函数 Test.Main(); public class Test //用户层,执行输入等操作 { public static void Main() { Calculate cc = new Calculate(); Function fc = new Function(); int result1 = cc.CalculateTest(2, 3, fc.GetSum); Console.WriteLine("调用了开发人员的加法函数,处理后返回结果:" + result1); int result2 = cc.CalculateTest(2, 3, fc.GetMulti); Console.WriteLine("调用了开发人员的乘法函数,处理后返回结果:" + result2); Console.ReadKey(); } } public class Function { public int GetSum(int a,int b) { Console.WriteLine("进入加法运算"); int c = a + b; Console.WriteLine("加法运算完毕"); return c; } public int GetMulti(int a, int b) { Console.WriteLine("进入乘法运算"); int c = a * b; Console.WriteLine("乘法运算完毕"); return c; } } public class Calculate { public delegate int CalculateWay(int a, int b); public int CalculateTest(int num1, int num2, CalculateWay calculate) { Console.WriteLine("收到传入参数:" + num1 + "and" + num2); int c = calculate(num1,num2); Console.WriteLine("传入方法执行完毕"); return (c); } }
这个实现太简单了还是记录下,后续有其他更经典的方式再做记录
方式二
// See https://aka.ms/new-console-template for more information using System.Text; Console.WriteLine("Hello, World!"); //C# 简单实现回调函数 Test test = new Test(); test.Main(); test.MQTTReceiver("12345"); public class Test //用户层,执行输入等操作 { public delegate void GetHeartDataDelegate(string model); //定义一个委托 public GetHeartDataDelegate GetHeartHandler; //MQTT接收数据处理 public void MQTTReceiver(string sendStr) { if (null != GetHeartHandler) { //省略转换 GetHeartHandler(sendStr); //调用委托函数 } } //外部调用 public void GetHeartDataCallback(string model) { //省略实现代码 Console.WriteLine("我是收到数据后的外部实现"); } public void Main() { GetHeartHandler = new GetHeartDataDelegate(GetHeartDataCallback); //绑定需要回调的函数 } } }