using System.Collections;using System.Collections.Generic;using UnityEngine;publicclassCSharp_学习委托 : MonoBehaviour
{privatedelegatevoidMyDelegate(string name);// Start is called before the first frame updatevoidStart(){MyDelegate a =newMyDelegate(Method);a("HelloWorld!");}publicvoidMethod(string str){print(str);}}
2、Action委托和Func委托
除了我们自己定义的委托之外,系统还给我们提供了一个内置的委托类型,Action和Func
using System;using UnityEngine;/*
* Action委托引用了一个Void返回类型的方法,
* Func委托引用了一个带有返回值的方法
*/publicclassCSharp_学习委托 : MonoBehaviour
{privatevoidGet(){print("***");}privatevoidGetString(string str){print(str);}privatevoidGetInt(int i1,int i2){print(i1+i2);}// Start is called before the first frame updatevoidStart(){//Action可以指向一个没有返回值没有参数的方法Action o = Get;o();//Action可以指向一个没有返回值有一个或多个参数的方法
Action<string> a = GetString;a("HelloWorld!");
Action<int,int> b = GetInt;b(6,8);//Func可以指向一个有返回值没有参数的方法
Func<int> c = FInt;print(c());//Func可以指向一个有返回值有一个或多个参数的方法
Func<int,string> d = FString;print(d(3));
Func<int,int,string> e = FuncString;print(e(6,8));}privateintFInt(){return1;}privatestringFString(int i){return"Hello:"+i;}privatestringFuncString(int i1,int i2){return("World:"+( i1 + i2));}}
3、拓展的冒泡排序
using UnityEngine;using System;/*
* 给自定义的类型做排序
*/publicclassEmployList:MonoBehaviour{//定义一个排序雇员薪水的方法,参数1:雇员类型的数组 //参数2:返回值为bool还有两个Employ参数的Func委托staticvoidComEmp(Employ[] array, Func<Employ, Employ,bool> CompareF){for(int i =0; i < array.Length -2; i++){for(int j =0; j < array.Length -1; j++){if(CompareF(array[j], array[j +1])==true){var tem = array[j];
array[j]= array[j +1];
array[j +1]= tem;}}}foreach(Employ item in array){print("名字:"+ item.Name +" , "+"薪水:"+ item.Salary);}}// Start is called before the first frame updatevoidStart(){//声明一个Employ类型的数组
Employ[] eArray =newEmploy[]{newEmploy("aaa",4500m),newEmploy("bbb",8300m),newEmploy("ccc",3700m),newEmploy("ddd",10500m),newEmploy("eee",7800m),};//调用ComEmp方法ComEmp(eArray, Employ.Compare);}}//雇员类,有名字和薪水两种属性classEmploy{privatestring name;privatedecimal salary;publicstring Name
{get{return name;}set{ name =value;}}publicdecimal Salary
{get{return salary;}set{ salary =value;}}//定义一个有两个参数的构造方法publicEmploy(string name,decimal salary){this.Name = name;this.Salary = salary;}//定义一个被Func委托CompareF指定的方法,比较两个对象的薪资的大小publicstaticboolCompare(Employ e1,Employ e2){if(e1.Salary > e2.Salary){returntrue;}else{returnfalse;}}}
4、多播委托
前面使用的委托都只包含一个方法的调用,但是委托也可以包含多个方法,这种委托叫做多播委托。
使用多播委托可以按照顺序调用多个方法;
多播委托只能得到调用的最后一个方法的返回值,因此我们一般把多播委托的返回类型声明为void。
voidA1(){print("A1");}voidA2(){print("A2");}privatevoidStart(){Action a = A1;
a += A2;a();//输出a1、a2
a -= A1;//如果a为空会报错if(a !=null){a();//输出a2}//取得多播委托中所有方法的委托
Delegate[] del = a.GetInvocationList();
del[0].DynamicInvoke();}
5、Lambda表达式
相当于匿名方法的简写形式。
delegateintDel(int i1,int i2);privateintA2(int i,int f){return i + f;}privatevoidStart(){//方法一 常规方式Del d =newDel(A2);print(d(45,36));}