(第三季)委托(201~202)203-Action委托207 多播委托 208 匿名方法

2024-03-18 02:08

本文主要是介绍(第三季)委托(201~202)203-Action委托207 多播委托 208 匿名方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

什么是委托?

  如果我们要把方法当做参数来传递的话,就要用到委托。简单来说委托是一个类型,这个类型可以赋值一个方法的引用。

声明委托

在C#中使用一个类分两个阶段,首选定义这个类,告诉编译器这个类由什么字段和方法组成的,然后使用这个类实例化对象。在我们使用委托的时候,也需要经过这两个阶段,首先定义委托,告诉编译器我们这个委托可以指向哪些类型的方法,然后,创建该委托的实例。

定义委托的语法如下:

  delegate void IntMethodInvoker(int x);

定义了一个委托叫做IntMethodInvoker,这个委托可以指向什么类型的方法呢?

  这个方法要带有一个int类型的参数,并且方法的返回值是void的。

定义一个委托要定义方法的参数和返回值,使用关键字delegate定义。

定义委托的其他案例:

  delegate double TwoLongOp(long first,longsecond);

  delegate string GetAString();

使用委托

privatedelegate string GetAString();

staticvoid Main(){

  int x = 40;

  GetAString firstStringMethod = newGetAString(x.ToString);

  Console.WriteLine(firstStringMethod());

}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//
using System.Text.RegularExpressions;namespace taotao
{class Class1{// 定义一个委托的类型 ,这个委托类型的名字叫做GetAString();private delegate string GetAString();static void Main(){int x = 40;// 使用委托类型 创建实例//GetAString a = new GetAString(x.ToString);  // a指向了x中的ToString()方法GetAString a = x.ToString;//string s = a(); // 通过委托实例去调用方法string s = a.Invoke();  // 通过invoke方法调用a所引用的方法Console.WriteLine(s);   // 通过委托类型调用一个方法,跟直接调用方法作用是一样的//Console.ReadKey();}}
}


在这里我们首先使用GetAString委托声明了一个类型叫做fristStringMethod,接下来使用new对它进行初始化,使它引用到x中的ToString方法上,这样firstStringMethod就相当于x.ToString,我们通过firstStringMethod()执行方法就相当于x.ToString()

通过委托示例调用方法有两种方式

  fristStringMethod();

  firstStringMethod.Invoke();

委托的赋值

GetAStringfirstStringMethod = new GetAString(x.ToString);只需要把方法名给一个委托的构造方法就可以了

GetAStringfirstStringMethod = x.ToString;也可以把方法名直接给委托的实例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//
using System.Text.RegularExpressions;namespace taotao
{class Class1{static void Main(){//实例我使用委托类型作为方法的参数PrintString method = Method1;PrintStr(Method1);method = Method2;PrintStr(Method2);Console.ReadKey();}private delegate void PrintString();static void PrintStr(PrintString print){print();}static void Method1(){Console.WriteLine("method1");}static void Method2(){Console.WriteLine("method2");}}
}



简单委托示例

定义一个类MathsOperations里面有两个静态方法,使用委托调用该方法
class MathOperations{public static double MultiplyByTwo(double value){return value*2;}public static double Square(double value){return value*value;}
}
delegate double DoubleOp(double x);
static void Main(){DoubleOp[] operations={ MathOperations.MultiplyByTwo,MathOperations.Square };for(int i =0;i<operations.Length;i++){Console.WriteLine("Using operations "+i);ProcessAndDisplayNumber( operations[i],2.0 );}
}
static void ProcessAndDisplayNumber(DoubleOp action,double value){double res = action(value);Console.Writeline("Value :"+value+" Result:"+res);
}

Action委托和Func委托

除了我们自己定义的委托之外,系统还给我们提供过来一个内置的委托类型,Action和Func

Action委托引用了一个void返回类型的方法,T表示方法参数,先看Action委托有哪些

Action

Action<inT>

Action<inT1,in T2>

Action<inT1,in T2 ....  inT16>多有16种类型哦

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace taotao
{class Program{static void Main(string[] args){Action a = PrintString;Action<string> b = PrintString;Action<int, int> c = PrintDouble;}static void PrintDouble(int i, int j) { }static void PrintInt(int i){ }static void PrintString(string str) { }static void PrintString(){Console.WriteLine("Hello world!");  //  系统内置(预定义)的一个委托类型,它可以//指向一个没有返回值,没有参数的方法//Action<int> a = PrintInt;}}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//
using System.Text.RegularExpressions;namespace taotao
{class Class1{static void PrintString(){Console.WriteLine("hello world!");}static void PrintString(int a){Console.WriteLine("hello world!");}static void PrintString(string a){Console.WriteLine("hello world!");}static void Double(int a , int b){Console.WriteLine(a + b);}static void Main(){// 返回值,没有参数的方法。// action是系统内(预定义)的一个委托类型,它可以指向一个没有Action a = PrintString;Action<int> b = PrintString;//定义了一个委托类型,该类型指向没有返回值,有一个参数int的方法。Action<string> c = PrintString;// Action最多有16个参数Action<int, int> d = Double;d(6, 8);// Action 可以后面通过泛型去指定action指向的多个参数的类型,参数的// 类型跟action后面的声明的委托类型是对应着的Console.ReadKey();}}
}


Func引用了一个带有一个返回值的方法,它可以传递0或者多到16个参数类型,和一个返回类型

Func<outTResult>

Func<inT,out TResult>

Func<intT1,inT2,,,,,,in T16,out TResult>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace taotao
{class Program{static void Main(string[] args){Func<int> a = Test1;//Func中的类型指定的是方法的返回值类型Console.WriteLine(a());//Func<string, int> b = Test2;    // func 最后一个类型是返回值类型,前面是参数类型(最多16个),先写参数类型,最后一个是返回值类型int j = b("sdfdsf");Console.ReadKey();}static int Test1(){return 1;}static int Test2(string str){Console.WriteLine(str);return 2;}}
}

多播委托

前面使用的委托都只包含一个方法的调用,但是委托也可以包含多个方法,这种委托叫做多播委托。使用多播委托就可以按照顺序调用多个方法,多播委托只能得到调用的最后一个方法的结果,一般我们把多播委托的返回类型声明为void。

  Action action1 = Test1;

  action2+=Test2;

  action2-=Test1;

多播委托包含一个逐个调用的委托集合,如果通过委托调用的其中一个方法抛出异常,整个迭代就会停止。  


取得多播委托中所有方法的委托


Actiona1 = Method1;

a1+=Method2;

Delegate[]delegates=a1.GetInvocationList();

foreach(delegated in delegates){

  //d();

  d.DynamicInvoke(null);

}

遍历多播委托中所有的委托,然后单独调用

/*猫 叫  老鼠跑,主人醒
*/using System;
namespace CatCry
{class MainClass{static void Test1(){Console.WriteLine("Test1");//throw new Exception();}static void Test2(){Console.WriteLine("Test2");}static void Main(){// 多播委托Action a = Test1;a += Test2; // 表示添加一个委托的引用//// a -= Test1;//a -= Test2; // 当一个委托没有指向任何方法的时候,调用的话会出现异常。//if (a != null)//    a();//Delegate[] delegates = a.GetInvocationList();foreach (var item in delegates){item.DynamicInvoke();}Console.ReadKey();}}
}

匿名方法

到目前为止,使用委托,都是先定义一个方法,然后把方法给委托的实例。但还有另外一种使用委托的方式,不用去定义一个方法,应该说是使用匿名方法(方法没有名字)。

Func<int,int,int>plus = delegate (int a,int b){

  int temp = a+b;

  return temp;

};

intres = plus(34,34);

Console.WriteLine(res);

在这里相当于直接把要引用的方法直接写在了后面,优点是减少了要编写的代码,减少代码的复杂性


/*猫 叫  老鼠跑,主人醒
*/using System;
namespace CatCry
{class MainClass{static int Test1(int arg1, int arg2){return arg1 + arg2;}static void Main(){//Func<int, int, int> plus = Test1;// 修改成: 匿名方法  的形式Func<int, int, int> plus = delegate (int arg1, int arg2){return arg2 + arg1;};// 匿名方法本质上是一个方法,只是没有名字,任何使用委托变量的地方都可以使用匿名方法赋值Console.ReadKey();}}
}



这篇关于(第三季)委托(201~202)203-Action委托207 多播委托 208 匿名方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/820864

相关文章

python获取指定名字的程序的文件路径的两种方法

《python获取指定名字的程序的文件路径的两种方法》本文主要介绍了python获取指定名字的程序的文件路径的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 最近在做项目,需要用到给定一个程序名字就可以自动获取到这个程序在Windows系统下的绝对路径,以下

JavaScript中的高级调试方法全攻略指南

《JavaScript中的高级调试方法全攻略指南》什么是高级JavaScript调试技巧,它比console.log有何优势,如何使用断点调试定位问题,通过本文,我们将深入解答这些问题,带您从理论到实... 目录观点与案例结合观点1观点2观点3观点4观点5高级调试技巧详解实战案例断点调试:定位变量错误性能分

Python中 try / except / else / finally 异常处理方法详解

《Python中try/except/else/finally异常处理方法详解》:本文主要介绍Python中try/except/else/finally异常处理方法的相关资料,涵... 目录1. 基本结构2. 各部分的作用tryexceptelsefinally3. 执行流程总结4. 常见用法(1)多个e

JavaScript中比较两个数组是否有相同元素(交集)的三种常用方法

《JavaScript中比较两个数组是否有相同元素(交集)的三种常用方法》:本文主要介绍JavaScript中比较两个数组是否有相同元素(交集)的三种常用方法,每种方法结合实例代码给大家介绍的非常... 目录引言:为什么"相等"判断如此重要?方法1:使用some()+includes()(适合小数组)方法2

504 Gateway Timeout网关超时的根源及完美解决方法

《504GatewayTimeout网关超时的根源及完美解决方法》在日常开发和运维过程中,504GatewayTimeout错误是常见的网络问题之一,尤其是在使用反向代理(如Nginx)或... 目录引言为什么会出现 504 错误?1. 探索 504 Gateway Timeout 错误的根源 1.1 后端

MySQL 表空却 ibd 文件过大的问题及解决方法

《MySQL表空却ibd文件过大的问题及解决方法》本文给大家介绍MySQL表空却ibd文件过大的问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考... 目录一、问题背景:表空却 “吃满” 磁盘的怪事二、问题复现:一步步编程还原异常场景1. 准备测试源表与数据

python 线程池顺序执行的方法实现

《python线程池顺序执行的方法实现》在Python中,线程池默认是并发执行任务的,但若需要实现任务的顺序执行,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋... 目录方案一:强制单线程(伪顺序执行)方案二:按提交顺序获取结果方案三:任务间依赖控制方案四:队列顺序消

SpringBoot通过main方法启动web项目实践

《SpringBoot通过main方法启动web项目实践》SpringBoot通过SpringApplication.run()启动Web项目,自动推断应用类型,加载初始化器与监听器,配置Spring... 目录1. 启动入口:SpringApplication.run()2. SpringApplicat

使用Java读取本地文件并转换为MultipartFile对象的方法

《使用Java读取本地文件并转换为MultipartFile对象的方法》在许多JavaWeb应用中,我们经常会遇到将本地文件上传至服务器或其他系统的需求,在这种场景下,MultipartFile对象非... 目录1. 基本需求2. 自定义 MultipartFile 类3. 实现代码4. 代码解析5. 自定

Python文本相似度计算的方法大全

《Python文本相似度计算的方法大全》文本相似度是指两个文本在内容、结构或语义上的相近程度,通常用0到1之间的数值表示,0表示完全不同,1表示完全相同,本文将深入解析多种文本相似度计算方法,帮助您选... 目录前言什么是文本相似度?1. Levenshtein 距离(编辑距离)核心公式实现示例2. Jac