委托

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

代码:

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");
} } }

  

.net基础—委托和事件的更多相关文章

  1. C#基础-委托与事件

    委托 delegate是申明委托的关键字 返回类型都是相同的,并且参数类型个数都相同 委托声明 delegate double DelOperater(double num1, double num2 ...

  2. C# 基础 - 委托、事件

    1. 委托 sequenceDiagram 方法->>委托: 返回值和入参一样 委托->>方法: 调用委托就是调用绑定的方法 delegate int NumTest(int ...

  3. .NET基础拾遗(4)委托、事件、反射与特性

    Index : (1)类型语法.内存管理和垃圾回收基础 (2)面向对象的实现和异常的处理基础 (3)字符串.集合与流 (4)委托.事件.反射与特性 (5)多线程开发基础 (6)ADO.NET与数据库开 ...

  4. 【.NET基础】--委托、事件、线程(3)

    之前的两篇文章我们了解了委托和事件,本文我们看一下线程. 1,一个窗体程序,默认拥有一个线程(相当于一个商店里面,只有一个店员),这个默认的线程叫做 UI线程/主线程. 2,进程和线程的关系: A,进 ...

  5. 转载 【.NET基础】--委托、事件、线程(3)

      之前的两篇文章我们了解了委托和事件,本文我们看一下线程. 1,一个窗体程序,默认拥有一个线程(相当于一个商店里面,只有一个店员),这个默认的线程叫做 UI线程/主线程. 2,进程和线程的关系: A ...

  6. 转载 【.NET基础】--委托、事件、线程(2) https://www.cnblogs.com/chengzish/p/4569912.html

    [.NET基础]--委托.事件.线程(2)   本文介绍event的使用以及原理,本文接上一篇文章的Demo继续[下载上一篇Demo] 上一篇我们在类(dg_SayHi.cs)里面定义代理了4个Del ...

  7. 转载 【.NET基础】--委托、事件、线程(1) https://www.cnblogs.com/chengzish/p/4559268.html

    [.NET基础]--委托.事件.线程(1)   1,委托 是存放方法的指针的清单,也就是装方法的容器 A, 新建winform项目[01委托],项目中添加dg_SayHi.cs 委托类 用于存储方法 ...

  8. .NET零基础入门05:委托与事件

    一:前言 本小节,我们需要停一停我们的小游戏开发,虽然它现在还不完美,还很简单,甚至还有BUG.但是,为了更好的理解C#,现在到了该深入了解一些基础知识的时候了. 当然,实际上,本小节内容对于零基础入 ...

  9. C#基础知识之事件和委托

    本文中,我将通过两个范例由浅入深地讲述什么是委托.为什么要使用委托.委托的调用方式.事件的由来..Net Framework中的委托和事件.委托和事件对Observer设计模式的意义,对它们的中间代码 ...

  10. 【.NET基础】--委托、事件、线程(2)

    本文介绍event的使用以及原理,本文接上一篇文章的Demo继续[下载上一篇Demo] 上一篇我们在类(dg_SayHi.cs)里面定义代理了4个Delegate,然后在Button的后台事件中 新建 ...

随机推荐

  1. 20230103~05code

    目录 U190849 最简分式 P5734 [深基6.例6]文字处理软件 P1104 生日 P4305 [JLOI2011]不重复数字 P8218 [深进1.例1]求区间和 P3397 地毯 P236 ...

  2. vue中aciton使用的自我总结

    一.需求: 我需要从后台中获取菜单列表在路由守卫中进行限制. 二.遇到的问题: action中setMenuData的方法如下: actions: { setMenuData(context){ ge ...

  3. vim 小记录

    将str1批量替换成str2 , 特殊符号前用转译符 \ :%s/str1/str2/g

  4. PID名词解析

    在工程实际中,应用最为广泛的调节器控制规律为比例.积分.微分控制,简称PID控制,又称PID调节. 当被控对象的结构和参数不能完全掌握,或得不到精确的数学模型时,控制理论的 其它技术难以采用时,系统控 ...

  5. ESLint未定义报错

    vue框架, ---   .eslintrc.js : module.exports = { root: true, env: { node: true }, 'extends': [ 'plugin ...

  6. jenkins-构建触发器之定时构建和轮询 SCM

    前言 最近搭建自动化框架,跑自动化用例每次都得用手工点击构建任务,我们希望能每天固定时间跑,这样就不用管了,坐等收测试报告结果就行 定时构建语法 五颗星,中间用空格隔开 * * * * * 第一颗*表 ...

  7. 爬B站并保存成csv文件。提供数据

    """b站排行榜爬虫(scrapy)https://www.bilibili.com/ranking#!/all/0/0/7/爬取编号,标题,url,综合评分,播放量,评 ...

  8. mac使用expect登录跳板机后的机器

    两个文档 #!/usr/bin/expect -f #连接文件名字记录 set ip [lindex $argv 0] catch {spawn ssh 1.1.1.1}## ip地址换成自己的 ex ...

  9. Jenkins+Git+Gitlab+Ansible 持续集成和自动部署

  10. errgroup.Group

    在一组 Goroutine 中提供了同步.错误传播以及上下文取消的功能,我们可以使用如下所示的方式并行获取网页的数据: package main import ( "fmt" &q ...