1. 主页
  2. 文档
  3. C#进阶
  4. 第五章 委托
  5. 第一节 委托初体验

第一节 委托初体验

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpAdvancedDelegate
{
    /// <summary>
    /// 1  委托是一个引用类型,其实它是一个类,保存方法的指针,他指向一个方法,当我们调用委托
    /// 的时候这个方法就立即被执行。
    /// </summary>
    delegate void HelloDelegate(string msg); //委托定义【参数个数和返回值要与Hello函数一致】
    class Program
    {
        static void Main(string[] args)
        {
            HelloDelegate helloDelegate = new HelloDelegate(Hello); //创委托实例【传Hello函数名】
            helloDelegate("hello delegate !");  //调用委托【参数与Hello函数参数一致】


            Console.Read();
        }

    //在类内新建一个静态方法,因为是写在Program类中所以要静态方法。
        public static void Hello(string str)
        {
            Console.WriteLine(str);
        }        
    }
}

不用委托来实现类中函数的调用;这种普通的方式learnLegegateStu.Price >= 599是固定的,只能通过修改源码来修改。

 class LearnLegegateStu
    {
        public int Id { get; set; }
        public string StuName { get; set; }
        public int Price { get; set; }
        public static void CSharpStu(List<LearnLegegateStu> learnLegegateStus)
        {
            foreach (LearnLegegateStu learnLegegateStu in learnLegegateStus)
            {
                if (learnLegegateStu.Price >= 599)
                {
                    Console.WriteLine(learnLegegateStu.StuName+"是学员");
                }
            }
        }
    }

在Main()函数中的调用

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 = 299 });
            learnLegegateStus.Add(new LearnLegegateStu() { Id = 4, StuName = "dog", Price = 499 });
            learnLegegateStus.Add(new LearnLegegateStu() { Id = 3, StuName = "pig", Price = 599 });
            LearnLegegateStu.CSharpStu(learnLegegateStus);  //由于是静态方法是类名.静态方法名+参数;
}
这篇文章对您有用吗?

我们要如何帮助您?