委托可以把部分代码孤立出来写成一个函数,达到灵活应用的目的。在一些框架中有较多的应用。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharpAdvancedDelegate
{
/// <summary>
/// 1 委托是一个引用类型,其实它是一个类,保存方法的指针,他指向一个方法,当我们调用委托
/// 的时候这个方法就立即被执行。
/// </summary>
class Program
{
static void Main(string[] args)
{
Console.WriteLine("==================================");
List<LearnLegegateStu> learnLegegateStus = new List<LearnLegegateStu>();
learnLegegateStus.Add(new LearnLegegateStu() { Id = 1, StuName = "tom", Price = 199 });
learnLegegateStus.Add(new LearnLegegateStu() { Id = 2, StuName = "cat", Price = 699 });
learnLegegateStus.Add(new LearnLegegateStu() { Id = 4, StuName = "dog", Price = 499 });
learnLegegateStus.Add(new LearnLegegateStu() { Id = 3, StuName = "pig", Price = 599 });
IsLeearnStu isLeearnStu = new IsLeearnStu(GetStu);//创委托实例,实现方法与委托关联
LearnLegegateStu.CSharpStu(learnLegegateStus,isLeearnStu); //由于是静态方法是类名.静态方法名+参数;
Console.Read();
}
//委托也是一个类,要实例化,在实例化时要与函数进行关联;
public static bool GetStu(LearnLegegateStu learnLegegateStu)
{
if (learnLegegateStu.Price>=599)
{
return true;
}
else
{
return false;
}
}
}
delegate bool IsLeearnStu(LearnLegegateStu learnLegegateStu); //定义委托
class LearnLegegateStu
{
public int Id { get; set; }
public string StuName { get; set; }
public int Price { get; set; }
public static void CSharpStu(List<LearnLegegateStu> learnLegegateStus,IsLeearnStu isLeearnStu)
{
foreach (LearnLegegateStu learnLegegateStu in learnLegegateStus)
{
if (isLeearnStu(learnLegegateStu))
{
Console.WriteLine(learnLegegateStu.StuName+"是学员");
}
}
}
}
}
![](http://doc.cntworld.cn:8080/wp-content/uploads/2023/05/1-26.png)