.Net 委托 delegate 学习

一、什么是委托:

委托是寻址方法的.NET版本,使用委托可以将方法作为参数进行传递。委托是一种特殊类型的对象,其特殊之处在于委托中包含的只是一个活多个方法的地址,而不是数据。

二、使用委托: 关键字:delegate

1.声明:

public delegate void DoNothing();//定义一个无返回值,无参数的委托

public delegate int GetNum(int i); //定义有一个返回值int ,参数int 的委托

2.创建方法:

public static void DoSome()//无参无返回值的方法
{
Console.WriteLine("DoSome");
}

public static int TotalNum(int num)//有一个返回值int ,参数int 的方法
{
return num * num;
}

3.注册委托:

DoNothing doNothing = new DoNothing(DoSome);

//或者直接写出DoNothing doNothing = DoSome;

GetNum getNum = AddNum;//注册委托

4.执行委托

doNothing.Invoke();//执行委托  也可以直接 doNothing();

Console.WriteLine(getNum.Invoke(10));//执行委托并且打印

三、委托的意义

传递方法;把方法包裹起来, 传递逻辑。异步多线程执行

四、.net framework3.5之后,系统定义好了2个委托,开发尽量使用框架自带委托,尽量使用Action和Func

Action 无返回值委托,Func 有返回值委托

Action要使用参数,就写Action<int,string,double> 最多可以到16个

Func要使用参数,就写成Func<int,string,double> 最多可以到17个, 最后一个为返回值,现在这个返回的就是double类型

Action act = DoSome;//Action 无返回值委托

act.Invoke();

Func<int,int> func = new Func<int,int>(TotalNum)  ;

func(10);

五、多播委托

Action doSome = new Action(DoSome);
doSome += new Action(DoSome);
doSome += DoSome;

doSome();//按顺序执行,最后结果是执行3次DoSome方法

doSome -= DoSome;//减少一次DoSome执行

doSome();//按顺序执行,最后结果是执行2次DoSome方法

多播委托,按顺序执行,多播委托,用Action, Func带返回值的只执行完后,只得到最后一个结果,所以没有意义。

委托使用案例:一个学生类,一个学生管理静态类,可以通过委托,实现学生集合的筛选

 public class Student
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public int ClassId { get; set; }

        public int Age { get; set; }
    }

    public static  class StudentManager
    {
        public static List<Student> students = new List<Student>()
        {
            new Student(){ Id=1,Name="张三",ClassId=1001,Age=15 },
            new Student(){ Id=2,Name="李四",ClassId=1001,Age=15 },
            new Student(){ Id=3,Name="王五",ClassId=1001,Age=15 },
            new Student(){ Id=4,Name="赵六",ClassId=1001,Age=15 },
            new Student(){ Id=5,Name="杨幂",ClassId=1001,Age=14 },
            new Student(){ Id=6,Name="范冰冰",ClassId=101,Age=14 },
            new Student(){ Id=7,Name="张学友",ClassId=1021,Age=14},
            new Student(){ Id=8,Name="张三1",ClassId=1021,Age=16 },
            new Student(){ Id=9,Name="张三2",ClassId=1001,Age=17 },
            new Student(){ Id=10,Name="张三3",ClassId=1001,Age=15 },
            new Student(){ Id=11,Name="张三4",ClassId=1001,Age=19 },
            new Student(){ Id=12,Name="张三5",ClassId=1001,Age=25 },
            new Student(){ Id=13,Name="张三6",ClassId=1003,Age=25 },
            new Student(){ Id=14,Name="张三7",ClassId=1003,Age=25 },
            new Student(){ Id=15,Name="张三8",ClassId=1003,Age=25 },
            new Student(){ Id=16,Name="张三9",ClassId=1003,Age=25 },
            new Student(){ Id=17,Name="张三0",ClassId=1003,Age=25 },
            new Student(){ Id=18,Name="张三11",ClassId=1003,Age=15 },
            new Student(){ Id=19,Name="张三a",ClassId=1011,Age=15 },
            new Student(){ Id=20,Name="张三b",ClassId=1011,Age=15 },
            new Student(){ Id=21,Name="张三c",ClassId=1011,Age=15 },
            new Student(){ Id=22,Name="张三d",ClassId=1011,Age=15 },
            new Student(){ Id=23,Name="张三e",ClassId=1011,Age=15 },
            new Student(){ Id=24,Name="张三f",ClassId=1011,Age=15 },
            new Student(){ Id=25,Name="张三g",ClassId=3001,Age=15 },
            new Student(){ Id=26,Name="张三h",ClassId=3001,Age=13 },
            new Student(){ Id=27,Name="张三i",ClassId=3001,Age=13 },
            new Student(){ Id=28,Name="张三j",ClassId=3001,Age=13 },
            new Student(){ Id=29,Name="张三k",ClassId=3001,Age=13 },
        };

        public static List<Student> FindStudents(Func<Student,bool> func)
        {
            List<Student> stus = new List<Student>();

            foreach (var item in students)
            {
                if (func(item))
                {
                    stus.Add(item);
                }
            }
            return stus;
        }

        /// <summary>
        /// 查找ClassId为3001的学生
        /// </summary>
        /// <param name="student">学生</param>
        /// <returns>是否为3001班级的学生</returns>
        public static bool GetClassId(Student student)
        {
            if (student.ClassId==3001)
            {
                return true;
            }

            return false;

        }
        /// <summary>
        /// 年龄大于20的学生
        /// </summary>
        /// <param name="student"></param>
        /// <returns></returns>
        public static bool GetBigAge(Student student)
        {
            if (student.Age>20)
            {
                return true;
            }
            return false;
        }
        /// <summary>
        /// 年龄大于15 并且ClassId为1021
        /// </summary>
        /// <param name="student"></param>
        /// <returns></returns>
        public static bool GetStuByClassIdAndAge(Student student)
        {
            if (student.Age > 15 && student.ClassId==1021)
            {
                return true;
            }
            return false;
        }

    }

下面这个是在Main方法中执行查询学生

//List<Student> stus = StudentManager.students;

            //Console.WriteLine("姓名---年龄---班级--编号");
            //foreach (var item in stus)
            //{
            //    Console.WriteLine(item.Name+"---"+item.Age+"---"+item.ClassId+"---"+item.Id);
            //}

            List<Student> stus1=  StudentManager.FindStudents(StudentManager.GetStuByClassIdAndAge);

            Console.WriteLine("姓名---年龄---班级--编号");
            foreach (var item in stus1)
            {
                Console.WriteLine(item.Name + "---" + item.Age + "---" + item.ClassId + "---" + item.Id);
            }

原文地址:https://www.cnblogs.com/Rookieflying/p/10386198.html

时间: 2024-08-29 10:32:23

.Net 委托 delegate 学习的相关文章

Unity3D游戏开发之委托(Delegate)

Unity3D游戏开发之委托(Delegate) 1.定义 delegate是C#中的一种类型,它实际上是一个能够持有对某个方法的引用的类.与其它的类不同,delegate类能够拥有一个签名(signature),并且它"只能持有与它的签名相匹配的方法的引用". 它允许你传递一个类A的方法m给另一个类B的对象,使得类B的对象能够调用这个方法m. delegate是面向对象.类型安全.可靠的受控(managed)对象.也就是说,运行时能够保证delegate指向一个有效的方法,你无须担心

C#用委托(Delegate)的BeginInvoke和EndInvoke方法操作线程

C#用委托(Delegate)的BeginInvoke和EndInvoke方法操作线程C# 2011-03-05 13:06:24 阅读19 评论0   字号:大中小 订阅 用委托(Delegate)的BeginInvoke和EndInvoke方法操作线程 在C#中使用线程的方法很多,使用委托的BeginInvoke和EndInvoke方法就是其中之一. BeginInvoke方法可以使用线程异步地执行委托所指向的方法.然后通过EndInvoke方法获得方法的返回值(EndInvoke方法的返回

c# 委托 delegate

委托是一种存储函数引用的类型,在事件和事件的处理时有重要的用途 通俗的说,委托是一个可以引用方法的类型,当创建一个委托,也就创建一个引用方法的变量,进而就可以调用那个方法,即委托可以调用它所指的方法. 使用委托 委托的使用需要以下步骤: 定义委托 delegate double ParocessDelegate(double param1,double param2); 委托的定义非常类似于函数,但不带函数体,且要使用delegate关键字.委托定义需要指明委托名称以及一个返回类型和一个参数列表

委托 delegate

c# 的委托就是说把函数当参数来传递. 这个在js完全就用不着搞什么委托东西,直接转就是了嘛.对不对!怎么录嘛! 一个函数,如果它的参数是函数,那么是这样子写的 public void method(Action<string, Int32> voidMethod, Func<string, Int32> returnMethod) Action<string, Int32> voidMethod 的意思是说这个将被传进来的函数是一个没有return的函数,就是publ

理解委托(delegate)及为什么要使用委托

理解委托(delegate)及为什么要使用委托 委托:是一种定义方法签名的类型. 当实例化委托时,您可以将其实例与任何具有兼容签名的方法相关联. 您可以通过委托实例调用方法. 上述为官方说法,理解起来比较难,举个生活中的例子: 某人有三子,让他们各自带一样东西出门,并带回一头猎物.上面一句话可以理解为父亲对儿子的委托:猎物 办法(工具 某工具)-->delegate 猎物(返回值) 带回猎物(委托名)(工具(参数类型) x)-->delegate int GetValue(int i)三个人执

关于C# 委托(delegate)与事件(event)的用法及事例

C#中的委托和事件对于新手可能会有一点难理解,所以先从一个小例子入手,以便能更好的理解其如何使用.有一个学生每天定闹钟在早上6点起床,所以当每天早上6点的时候,闹钟就会响起来,从而学生才会按时起床. 上面例子实际上包括2个类,一个是学生类(Student),一个是闹钟类(Ring).此时,让我们仔细想想,当闹钟到点后如何通知学生呢?当然不要说,闹钟响了,学生能听到这样的话23333,现在是写程序,一切用程序说话.也就是说当时间到了,闹钟类里应该有个给学生发消息的方法(OnSendMessage(

【温故知新】C#委托delegate

在c#的学习过程中,学到委托与事件总会迷糊一段时间,迷糊过后自然而就似懂非懂了~,所以最近我打算把以前所学的迷糊过的知识总结,温故知新,总结记录下来. 首先,我们来看一下msdn对委托的定义: delegate 关键字用于声明可用来封装命名方法的引用类型.委托大致类似于 C++ 中的函数指针:但是,委托是类型安全和可靠的. delegate 可让您传递一个函数作为参数.委托的类型安全要求作为 delegate 传递的函数具有与 delegate 声明相同的签名. 委托是事件的基础. 我们都知道,

组件接口(API)设计指南[3]-委托(delegate)和数据源协议(data-source protocols)

*返回目录阅读其他章节: http://blog.csdn.net/cuibo1123/article/details/39894477 委托(delegate)和数据源协议(data-source protocols) 委托协议是一个非常好的设计,它能让你用简单灵活的方式去实现MVC模式,并能增强松散耦合以及养成良好的API设计习惯. 这里是MGTileMenu的委托协议. 我们几乎可以在任何组件中利用经典的委托(delegate)和数据源协议(data-source protocols).如

【C#】委托-Delegate

C# 委托(Delegate) C# 中的委托(Delegate)类似于 C 或 C++ 中函数的指针.委托(Delegate) 是存有对某个方法的引用的一种引用类型变量.引用可在运行时被改变. 委托(Delegate)特别用于实现事件和回调方法.所有的委托(Delegate)都派生自 System.Delegate 类. 声明委托(Delegate) 委托声明决定了可由该委托引用的方法.委托可指向一个与其具有相同标签的方法. 例如,假设有一个委托: public delegate int My