委托(作用:解耦),lambda的演化
1.了解委托
MyDelegate类代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace MyDelegate
{
/// <summary>
/// 委托可以定义在类外面
/// </summary>
public delegate void OutNoReturnNoPara();
public delegate void OutNoReturnWithPara(int x, int y); class DelegateClass
{
/// <summary>
/// 1.声明委托,委托的参数与函数的参数必须一致
/// </summary>
public delegate void NoReturnNoPara();
public delegate void NoReturnWithPara(int x, int y);
public delegate string NoPara();
public delegate DateTime WithPara(string name,int size); public static void Show()//静态方法的委托只能调用静态方法
{
//2.实例化委托,这里的method实例化后就是一个Plus函数
NoReturnWithPara method = new NoReturnWithPara(Plus);//等价于NoReturnWithPara method = Plus;
//3.调用委托
method.Invoke(, );//等价于method(3, 4);
method.BeginInvoke(, ,null,null);//补充:新建一个线程,异步调用 }
public static void Plus(int x,int y)
{
Console.WriteLine("这里是Plus x={0} y={1}", x, y);
}
}
}
在Program使用DelegateClass.Show();
可以调用Plus这个方法
2.委托的用处
1)打招呼===》普通方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace MyDelegate
{
class GreetingClass
{public static void Greeting(string name,PeopleType type)//输入和谁打招呼,和这个人是哪个国家的人
{
if(type==PeopleType.Chinese)
{
Console.WriteLine("{0}早上好", name);
}
else if(type==PeopleType.English)
{
Console.WriteLine("{0}Morning", name);
}
else
{
throw new Exception("wrong PeopleType");
}
}
}public enum PeopleType //枚举,定义国家
{
Chinese,English
}
}
在Program使用GreetingClass.Greeting("kxy",PeopleType.Chinese);//kxy是一个中国人,所以使用PeopleType.Chinese
可以实现给不同国家的人打招呼用对应国家的语言
但是如果我们需要增加一种语言,则需要修改枚举PeopleType和函数Greeting
2)打招呼===》委托方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace MyDelegate
{
class GreetingClass
{ public static void GreetingChinese(string name)
{
Console.WriteLine("{0}早上好", name);
}
public static void GreetingEnglish(string name)
{
Console.WriteLine("{0}Morning", name);
}
}
public delegate void GreetingHandler(string name);
}
Program代码如下:
GreetingHandler handle = new GreetingHandler(GreetingClass.GreetingEnglish);//指明是哪国人
handle("flt");//输入人的名字
当需要增加一种新的语言时,直接增加一个Greeting*******函数就可以了,解除耦合
3.lambda的演化
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace MyDelegate
{
public class Student
{
public delegate void NoReturnWithPara(string name, DateTime now);
/// <summary>
/// 匿名函数向lambda演化的过程
/// </summary>
public static void show()
{
//普通委托
NoReturnWithPara method = new NoReturnWithPara(Study); //使用匿名函数
NoReturnWithPara method1 = new NoReturnWithPara(
delegate (string name, DateTime now)
{
Console.WriteLine("{0} {1}在学习", name, now);
}); //匿名函数向lambda演化,去掉delegate,加入=>
NoReturnWithPara method2 = new NoReturnWithPara(
(string name, DateTime now)=>
{
Console.WriteLine("{0} {1}在学习", name, now);
}); //匿名函数向lambda演化,去掉类型,因为委托函数会自动标识类型
NoReturnWithPara method3 = new NoReturnWithPara(
(name, now) =>
{
Console.WriteLine("{0} {1}在学习", name, now);
}); //匿名函数向lambda演化,去掉new,这也是最终形式
NoReturnWithPara method4 = (name, now) =>
{
Console.WriteLine("{0} {1}在学习", name, now);
}; //匿名函数向lambda演化,如果方法体只有一行,可以去掉大括号
NoReturnWithPara method10 = (name, now) => Console.WriteLine("{0} {1}在学习", name, now);
method10("zjx",DateTime.Now);
} public static void Study(string name, DateTime now)
{
Console.WriteLine("{0} {1}在学习",name,now);
}
}
}
4.其他多种委托使用lambda
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace MyDelegate
{
public class Student
{
public delegate void NoReturnWithPara(string name, DateTime now);
public delegate int WithReturnWithPara(int x,int y);
public delegate string WithReturnNoPara();
/// <summary>
/// 委托向lambda演化的过程
/// </summary>
public static void show()
{//没有参数,返回一个string类似,可以省略return和大括号
WithReturnNoPara meth = () => "我爱学习"; //有两个int参数,返回int类型
WithReturnWithPara meth2 = (x, y) => x + y; ///////////////////////////在开发中基本不需要自己定义委托,可以使用下面方法/////////////////////////////////
//Action是一个委托,无返回值 <定义参数类型>
Action action1 = () => { };//无参数无返回值
Action<string> action2 = s =>{ };//有参数无返回值,且只有一个参数时可以去掉参数的小括号
Action<int, string, DateTime> action3 = (x, y, z) => { };//可以有多个参数,自定义 //Func是一个委托,有返回值 <定义参数类型,和返回值类型>
Func<string> func1 = () => "我爱学习"; //<只有一个类型>,该类型是指返回值类型
Func<string, int, DateTime> func2 = (x, y) => DateTime.Now;//<参数类型,参数类型,返回值类型>
}
}
}
5.lambda向linq的扩展
public static void LinqShow()
{
//-----------------------定义一个1到99的数组-------------------------
List<int> intlist = new List<int>();
for(int i=;i<;i++)
{
intlist.Add(i);
}
//-----------------------打印大于55的数字----------------------------
//-----------------------传统方法-----------------------------------
foreach(int i in intlist)
{
if(i>)
{
Console.WriteLine(i);
}
}
//-----------------------linq方法-----------------------------------
var linq = from s in intlist
where s >
select s;
foreach(int i in linq)
{
Console.WriteLine(i);
}
//-----------------------linq方法扩展为lambda------------------------
foreach (int i in intlist.Where<int>(m => m > ))
{
Console.WriteLine(i);
}
//上面foreach可详写为:
foreach (int i in intlist.Where<int>(//Where是Linq下的一个Func委托,有返回值
(m) => { return m > ; }//匿名函数,使用lambda表达式
)
)
{
Console.WriteLine(i);
}
}
委托(作用:解耦),lambda的演化的更多相关文章
- C++ lambda的演化
翻译自https://www.bfilipek.com/2019/02/lambdas-story-part1.html与https://www.bfilipek.com/2019/02/lambda ...
- C++实现委托机制(三)——lambda表达式封装
C++.引言: 其实原本没打算写这一章的,不过最后想了想,嗯还是把lambda表达式也一并封装进去,让这个委托也适应lambda表达式的注册.不过在之前还是需要先了解lamb ...
- C#多线程+委托+匿名方法+Lambda表达式
线程 下面是百度写的: 定义英文:Thread每个正在系统上运行的程序都是一个进程.每个进程包含一到多个线程.进程也可能是整个程序或者是部分程序的动态执行.线程是一组指令的集合,或者是程序的特殊段,它 ...
- C#委托多播、Lambda表达、多线程、任务
class Program { static void Main(string[] args) { Action<double> ops = MathOperations.Mutiply; ...
- 委托-异步调用-泛型委托-匿名方法-Lambda表达式-事件【转】
1. 委托 From: http://www.cnblogs.com/daxnet/archive/2008/11/08/1687014.html 类是对象的抽象,而委托则可以看成是函数的抽象.一个委 ...
- (28)C#委托,匿名函数,lambda表达式,事件
一.委托 委托是一种用于封装命名和匿名方法的引用类型. 把方法当参数,传给另一个方法(这么说好理解,但实际上方法不能当参数,传入的是委托类型),委托是一种引用类型,委托里包含很多方法的引用 创建的方法 ...
- 委托初级篇——lambda表达式的推导
public delegate void ConsoleWriteStr(string name,DateTime now); public delegate int DelegateAdd(int ...
- 委托、回调 Lambda表达式书写方式
- .NET中那些所谓的新语法之三:系统预定义委托与Lambda表达式
开篇:在上一篇中,我们了解了匿名类.匿名方法与扩展方法等所谓的新语法,这一篇我们继续征程,看看系统预定义委托(Action/Func/Predicate)和超爱的Lambda表达式.为了方便码农们,. ...
随机推荐
- python解决json序列化时间格式
简单实例 import json from datetime import datetime from datetime import date info = { "name": ...
- postgresql安装概览
先从官网下载解压包:https://www.enterprisedb.com/download-postgresql-binaries 这种是解压后,进行配置就可以使用. 另外一种是要用./confi ...
- python基础-格式化时间
module datatime用strftime格式化时间import datetimedatetime.datetime.now() 返回microsecond,要修改datetime.dateti ...
- HTML学习笔记Day10
一.Form表单补充(收集用户信息) 1.button按钮(不进行提交) 1)语法1:<input type="button" value="按钮内容" ...
- (BFS/DFS) leetcode 200. Number of Islands
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surro ...
- node.js(基础四)_express基础
一.前言 本次内容主要包括: 1.express的基本用法 2.express中的静 ...
- Calendar 类 案例 和 闰年的计算
Calendar 类 是一个抽象类 getInstance()直接返回子类对象 直接调用 主要方法:get set add 代码如下: package cn.lijun.demo; import ja ...
- 2.Diango学习
##创建应用 python manage.py startapp blog !!创建应用后要添加应用,名称不允许与模块名称相同 ##应用目录结构 ##文件介绍 1. 2. 3. 4. 5. 6. ## ...
- qml: 以鼠标为中心进行放缩;
import QtQuick 2.9 import QtQuick.Window 2.2 import QtQuick.Controls 2.2 Window { visible: true widt ...
- python自动化开发-[第四天]-函数
今日概要: - 函数对象 - 函数嵌套 - 命名空间和作用域 - 闭包 - 装饰器 - 迭代器 - 生成器 - 内置函数 一.函数对象 1.函数对象的定义: 函数是第一类对象,即函数可以当作数据传递 ...