1)定义Callback接口
public interface IBack { int run(int a, int b); }
2)定义类,实现Callback接口
public class AddCallback : IBack { public int run(int a, int b) { Thread.Sleep(5000); return a + b; } }
3)定义调用Callback函数的类
public class PrintResult { IBack CallbackAdd = null; public PrintResult(IBack CallbackAdd) { this.CallbackAdd = CallbackAdd; } public void PrintAdd(int a, int b) { Console.WriteLine($"{a}+{b}={ this.CallbackAdd.run(a, b)}"); } }
4)Main函数
static void Main(string[] args) { PrintResult pr = new PrintResult(new AddCallback()); pr.PrindAdd(1, 2); }