1.主程序代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CallBackTest
{
internal class Program
{
//定义委托
public delegate void MyCallBack(String name);
static void Main(string[] args)
{
//将另一个方法名做为传参
Cat.CatName(Person);
Console.ReadKey();
}
//被回调的方法
private static void Person(string name)
{
Console.WriteLine(name+"是我的宠物");
}
}
}
2.定义Cat类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using static CallBackTest.Program;
namespace CallBackTest
{
internal class Cat
{
public static void CatName(MyCallBack myCallBack)
{
string name = "图图";
Console.WriteLine("我的猫叫"+name);
//通过回调传参给被回调的方法
myCallBack(name);
}
}
}
3.最终运行结果