1、委托初体验
namespace ConsoleApp1
{
delegate void HelloDelegate(string msg); //定义委托
public class MainClass
{
///1--委托初体验
///委托是一个引用类型,其实他是一个类型,保存方法的指针,他指向一个方法,
///当我们调用委托的时候这个方法就立即被执行
public static void Main()
{
HelloDelegate helloDelegate = new HelloDelegate(Hello);//创建委托实例,参数为函数名
// helloDelegate.Invoke("您好委托!");
helloDelegate("您好委托!");//调用委托
Console.ReadKey();
}
public static void Hello(string str)
{
Console.WriteLine(str);
}
}
}
2、对于局部数据处理,实现分层处理数据
namespace ConsoleApp1
{
delegate bool IsCsharpVip(LearnVip learnVip);//定义委托
class MainClass
{
///1--委托初体验
///委托是一个引用类型,其实他是一个类型,保存方法的指针,他指向一个方法,
///当我们调用委托的时候这个方法就立即被执行
public static void Main()
{
List<LearnVip> learnVips = new List<LearnVip>();
learnVips.Add(new LearnVip() { Id = 1, StudentName = "Ant1号", Price = 299 });
learnVips.Add(new LearnVip() { Id = 1, StudentName = "Ant2号", Price = 399 });
learnVips.Add(new LearnVip() { Id = 1, StudentName = "Ant3号", Price = 599 });
learnVips.Add(new LearnVip() { Id = 1 , StudentName = "Ant4号", Price = 599 });
IsCsharpVip isCsharpVip = new IsCsharpVip(GetVip);
LearnVip.CsharpVip(learnVips, isCsharpVip);
Console.ReadKey();
}
public static bool GetVip(LearnVip learnVip)
{
if (learnVip.Price == 599)
return true;
else
return false;
}
public static bool GetVip2(LearnVip learnVip)
{
if (learnVip.Price == 5999)
return true;
else
return false;
}
}
class LearnVip
{
public int Id { get; set; }
public string StudentName { get; set; }
public int Price { get; set; }
public static void CsharpVip(List<LearnVip>learnVips,IsCsharpVip isCsharpVip)
{
foreach(LearnVip learnVip in learnVips)
{
if(isCsharpVip(learnVip))
Console.WriteLine(learnVip.StudentName + "是VIP学员!");
}
}
}
}