C# For Unity 编程笔记(委托)

1.委托

//事例中的代码均不是严格的代码规范,只作为理解参考
委托定义:
1 //定义一个委托,参数一个,类型为int,返回值为void
2 delegate void Test(int x);
3 //定义一个和委托返回值和参数类似一致的函数,并赋予给委托
4 void TestFunction(int x){}
5 Test = TestFunction;
// 创建方法二 
delegate void TestStr();
//实例化委托,并将符合条件的方法填入,s() == xxx.ToString() == s.Invoke();
TestStr s = new TestStr(xxx.ToString);
 
委托作为参数:(模仿回调函数)
 
//声明一个委托
delegate void CallHandler();
 
//CallHandler类型的委托作为参数
 1 void OnComplete(CallHandler call)
 2 {
 3      call();
 4 }
 5  
 6 //符合委托的一个函数
 7 void Test(){}
 8  
 9 void Main()
10 {
11      OnComplete(Test);
12 }
 
C#内置的委托(内置的委托几乎可以指向所有的方法)
1.Action委托(永远没有返回值)
例子:
1 // Action 是一个可以指向一个没有返回值,没有参数的一个委托
2 Action a = Test;
3 void Test(){}
1 // Action<T>是一个可以指向一个没有返回值,有T类型的参数的一个委托
2 Action<int> b = TestInt;
3 void TextInt(int x){}
1 //多参数和Action<T>类似,写法诸如Action<T , N  , S>
2 Action<string , int> c = TestStr;
3 void TestStr(string str , int i){}
PS:参数最多支持16个参数
 
2.Func委托(必须有返回值)
 
 1 //泛型里面的参数为函数的返回值(泛型必须有参数)
 2 Func<int> a = Test;
 3 int Test(){}
 4  
 5 //最后一个类似为返回值,前面的类型为参数类型
 6 Func<string ,int> b = Test;
 7 int Test(string str){}
 8  
 9 //多参数情况,最后一个为返回值,函数的参数也必须按委托的参数顺序来
10 Func<string ,string ,int> c = Test;
11 int Test(string ,str1,string str2){}
PS:参数最多支持16个参数
 
多播委托(一个委托指向多个函数,一般返回值为空,因为不能返回所有的返回值)
例子:
 1 void Test1(){print("Test1")}
 2 void Test2(){print("Test2")}
 3  
 4 Action a = Test1();
 5 a += Test2();
 6 print(a);//输出Test1,Test2
 7  
 8 a -= Test2();
 9 print(a);//输出Test1
10  
11 //PS:如果委托是有返回值的,则返回值为所添加的最后一个函数的返回值
12 //PS:如果加入的函数中只要有一个出现异常,则所有的函数运行结束
13 int Test3{return 3}
14 int Test4{return 4}
15 Func<int> b = Test3;
16 b += Test4;
17 print(b);//输出 4
原文地址:https://www.cnblogs.com/seabrea/p/4812920.html