.net基础—委托和事件

委托

委托是一种引用类型,表示对具有特定参数列表和返回类型的方法的引用。 在实例化委托时,可以将其实例与任何具有兼容签名和返回类型的方法相关联。 可以通过委托实例调用方法。
可以将任何可访问类或结构中与委托类型匹配的任何方法分配给委托。 该方法可以是静态方法,也可以是实例方法。 此灵活性意味着可以通过编程方式来更改方法调用,还可以向现有类中插入新代码。

代码:

using System;

namespace Test03
{
    internal class Program
    {
        static void Main(string[] args)
        {

            MyDelegate myDelegate = new MyDelegate();
            myDelegate.Show();


            Console.ReadKey();
        }
    }

    public class MyDelegate
    {
        //声明委托
        //public delegate void NoReturnNoPara<T>(T t);
        //public delegate void NoReturnWithPara(int x, int y);
        public delegate void NoReturnNoPara();


        public void Show()
        {
            {
                //委托的实例化 (传递的方法要与定义委托的返回值和参数相同)
                NoReturnNoPara method = new NoReturnNoPara(this.DoNothing);
                //委托实例的调用
                method.Invoke();
                //调用 方式二
                //method();
            }
        }

        private void DoNothing()
        {
            Console.WriteLine("This is DoNothing");
        }

        private static void DoNothingStatic()
        {
            Console.WriteLine("This is DoNothingStatic");
        }

    }

} 

委托应用实例

假如现在有一个数据集,要对其中的数据按照相应的掉进进行筛选。代码如下:

namespace Test03
{
    internal class Program
    {
        static void Main(string[] args)
        {

            var dataList = GetStudentList();
            {
                //查询年龄大于20
                List<Student> result = new List<Student>();
                foreach (var item in dataList)
                {
                    if (item.Age > 20)
                    {
                        result.Add(item);
                    }
                }
                Console.WriteLine($"年龄大于20的共有{result.Count}人");
            }
            {
                //查询二班中年龄大于18的
                List<Student> result = new List<Student>();
                foreach (var item in dataList)
                {
                    if (item.ClassId == 2 && item.Age > 18)
                    {
                        result.Add(item);
                    }
                }
                Console.WriteLine($"二班中年龄大于18的共有{result.Count}人");
            }

            //查询姓名长度大于2的
            /*
             * 具体代码和上面的类似
             */

            

            Console.ReadKey();
        }


        /// <summary>
        /// //初始化数据
        /// </summary>
        /// <returns></returns>
        public static List<Student> GetStudentList()
        {
            List<Student> studentList = new List<Student>()
            {
                new Student()
                {
                    Id = 1,
                    Name ="萧峰",
                    ClassId = 1,
                    Age =23
                },
                new Student()
                {
                    Id = 2,
                    Name ="段誉",
                    ClassId = 1,
                    Age =22
                },
                new Student()
                {
                    Id = 3,
                    Name ="虚竹",
                    ClassId = 1,
                    Age =21
                },
                new Student()
                {
                    Id = 4,
                    Name ="王语嫣",
                    ClassId = 2,
                    Age =21
                },
                new Student()
                {
                    Id = 5,
                    Name ="阿紫",
                    ClassId = 2,
                    Age =18
                },
                new Student()
                {
                    Id = 6,
                    Name ="阿朱",
                    ClassId = 2,
                    Age =22
                }
            };
            return studentList;
        }

    }

} 

对于上面代码,可以使用委托将上面的代码进行优化:

using System;
using System.Collections.Generic;

namespace Test03
{
    //声明委托
    public delegate bool ThanDelegate(Student student);

    class Program
    {
        static void Main(string[] args)
        {
            //调用
            DemoDelegate demo = new DemoDelegate();
            demo.Show1();

            Console.ReadKey();
        }

    }

    #region 委托示例
    public class DemoDelegate
    {
        public void Show1()
        {
            var dataList = StudentList.GetStudentList();
            ThanDelegate method = new ThanDelegate(Than);
            var result = this.GetListDelegate(dataList, method);
            Console.WriteLine($"年龄大于20的共有{result.Count}人");
        }

        /// <summary>
        /// 通的筛选方法
        /// </summary>
        /// <param name="source">数据源</param>
        /// <param name="method">委托</param>
        /// <returns></returns>
        private List<Student> GetListDelegate(List<Student> source, ThanDelegate method)
        {
            List<Student> result = new List<Student>();
            foreach (Student student in source)
            {
                if (method.Invoke(student))
                {
                    result.Add(student);
                }
            }
            return result;
        }

        /// <summary>
        /// 查询年龄大于20
        /// </summary>
        private bool Than(Student student)
        {
            return student.Age > 20;
        }
    }

    #endregion


    #region 数据
    class StudentList
    {
        /// <summary>
        /// //初始化数据
        /// </summary>
        /// <returns></returns>
        public static List<Student> GetStudentList()
        {
            List<Student> studentList = new List<Student>()
            {
                new Student()
                {
                    Id = 1,
                    Name ="萧峰",
                    ClassId = 1,
                    Age =23
                },
                new Student()
                {
                    Id = 2,
                    Name ="段誉",
                    ClassId = 1,
                    Age =22
                },
                new Student()
                {
                    Id = 3,
                    Name ="虚竹",
                    ClassId = 1,
                    Age =21
                },
                new Student()
                {
                    Id = 4,
                    Name ="王语嫣",
                    ClassId = 2,
                    Age =21
                },
                new Student()
                {
                    Id = 5,
                    Name ="阿紫",
                    ClassId = 2,
                    Age =18
                },
                new Student()
                {
                    Id = 6,
                    Name ="阿朱",
                    ClassId = 2,
                    Age =22
                }
            };
            return studentList;
        }
    }
    #endregion

} 

 

Student:

public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int ClassId { get; set; }
        public int Age  { get; set; }


        public void Study()
        {
            Console.WriteLine("This is Study");
        }

        public static void StudyStatic()
        {
            Console.WriteLine("This is StudyStatic");
        }

        public static void Show()
        {
            Console.WriteLine("Hello");
        }
    }

  

事件

namespace TestEvent
{
    public delegate void MyDelegate(string name);

    class Program
    {
        static void Main(string[] args)
        {
            EventSource test = new EventSource();
            test.TestEvent();

            Console.ReadKey();
        }
    }

    public class EventSource
    {
        public event MyDelegate EventDelegate;

        public void SetCustomer(string name)
        {
            Console.WriteLine($"Hello,{name}");
        }

        public void TestEvent()
        { 
            EventSource source = new EventSource();
            source.EventDelegate += new MyDelegate(source.SetCustomer);
            source.EventDelegate("TanYongJun");
        }

    }

}

  

posted @ 2022-02-12 22:07  #谭  阅读(151)  评论(0)    收藏  举报