0
点赞
收藏
分享

微信扫一扫

C#——委托

绪风 2022-02-15 阅读 66

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学员!");
            }
        }
    }
}
举报

相关推荐

C#之委托

C#委托总结

C#事件委托

C#中的委托

C# 委托与事件

【C#】委托和事件

0 条评论