委托的简单使用
2022/3/1 6:23:14
本文主要是介绍委托的简单使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
在说明委托之前,我们先直接来个简单的例子,假如现在你要去筛选一个杯子的信息,可以提供给你关于杯子的信息有如:杯子的价格、杯子的评分等。暂且先以前两项为主。现让你找出价格最高的杯子和评分最高的杯子,那么对应的代码其实很简单,如下:
先定义有关杯子的信息:
public class Cup { public int price; public int grade; public Cup(int price,int grade) { this.price = price; this.grade = grade; } }
- 在定义获取杯子最高价格和最高评分的方法:
public int GetMostGrade(Cup[] cups) { int maxGrade = cups[0].grade; for (int i = 1; i < cups.Length; i++) { if (cups[i].grade > maxGrade) { maxGrade = cups[i].grade; } } return maxGrade; } public int GetMostPrice(Cup[] cups) { int maxPrice = cups[0].price; for (int i = 1; i < cups.Length; i++) { if (cups[i].price > maxPrice) { maxPrice = cups[i].price; } } return maxPrice; }
- 最后我们可以在Start()方法里面测试(该脚本是在Unity项目中测试的)
void Start() { Cup[] cups = { new Cup(1, 5), new Cup(4, 2), new Cup(6, 3) }; int maxPrice = GetMostPrice(cups); int maxGrade = GetMostGrade(cups); Debug.Log("MaxPrice " + maxPrice); Debug.Log("MaxGrade " + maxGrade); }
- 我们运行程序,得到以下信息:
- 嗯,看起来似乎没有什么问题。也能正确打印信息。但是,你可能注意到就是代码部分看起来有过多的冗余,没错,正是这样。我们在编写获取杯子价格和评分的方法的时候,运用到的运算逻辑都是一样的,唯一的区别就是比较的因素不同,即一个是价格一个是评分。假如现在我们需要添加一个筛选的信息,比如杯子的销量好了,那按照上面的逻辑,是不是又要添加一个GetMostSlaesVolume()方法,然后将GetMosePrise()方法里的代码Copy进去,将cup.prise改为cup.laesVolume;假如有几百个这样的方法,那么冗余量是不是大大增加。那怎么办嘞,我们如何来精简这些重复的代码?
我们思考一下,不难发现,其实只要将方法中相同的部分保留,不同的部分给提取出来,然后参数化,针对不同的需求,我们只需要传入不同的参数就可以了。那么本例中的“不同部分”就是杯子的各个信息了。我们不妨定义一类方法,很简单,即获取杯子的信息
public int GetPrice(Cup cup) { return cup.price; } public int GetGrade(Cup cup) { return cup.grade; }
- 上面方法的返回值就是我们需要传入到 “获取最大值的方法” 中的参数了,是不。上面也说到了,其实就是传入各个因素。那我们如何传入这些参数呢,没错,就是用到标题说的委托了,我们定义并声明和上面方法匹配的委托:
public delegate int StudentDelegate(Cup cup); public StudentDelegate myDelegate;
- 然后我们改写原本的筛选逻辑,这次我们以委托的方式传入参数
public int GetMostElement(StudentDelegate studentDelegate,Cup[] cups) { int maxElement = studentDelegate(cups[0]); for (int i = 1; i < cups.Length; i++) { if(studentDelegate(cups[i]) > maxElement) { maxElement = studentDelegate(cups[i]); } } return maxElement; }
- 接着,在Start()方法里改写测试代码:
void Start() { Cup[] cups = { new Cup(1, 5), new Cup(4, 2), new Cup(6, 3) }; int maxPrice = GetMostElement(GetPrice, cups); int maxGrade = GetMostElement(GetGrade, cups); Debug.Log("MaxPrice " + maxPrice); Debug.Log("MaxGrade " + maxGrade); }
- 可以看到,当我们有新的筛选需求时,只要往方法里注册不同的委托参数即可。这样一来,当添加新的类似需求时,也可以快速添加,且不会有代码冗余。另外,也是符合开闭原则的。
输出的结果也是和上面的一样,就不贴图了。
这篇关于委托的简单使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?