在说明委托之前,我们先直接来个简单的例子,假如现在你要去筛选一个杯子的信息,可以提供给你关于杯子的信息有如:杯子的价格、杯子的评分等。暂且先以前两项为主。现让你找出价格最高的杯子和评分最高的杯子,那么对应的代码其实很简单,如下:
先定义有关杯子的信息:
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; }
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); }
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; }
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); }