C# 委托&事件

之前关于事件这块理解一直不是很好,正好有空复习,整理记录一下

委托:可以将与自身形式相同(返回参数相同;传入参数相同)的方法当成参数进行传递。

 1 using UnityEngine;
 2 using System.Collections;
 3 
 4 //委托测试
 5 public class Test : MonoBehaviour {
 6 
 7     /*定义委托
 8      * 可以传递函数
 9      * 相当于定义一个模板
10      * 符合模板的函数可以利用这个委托来使用
11      * */
12     delegate int Calculate(int _a, int _b);
13 
14     void Start () 
15     {
16         //创建委托,传入 Add 表示使用当前的委托相当于使用 Add 方法
17         Calculate c = new Calculate(Add);
18 
19         //使用委托
20         int d = c(1, 2);
21 
22         print(d);
23     }
24 
25     int Add(int _a, int _b)
26     {
27         return _a + _b;
28     }
29 
30     int Sub(int _a, int _b)
31     {
32         return _a - _b;
33     }
34 }

事件

事件的订阅:当事件触发时,执行指定的方法。

在使用Unity的情况下,定义一个按钮点击事件,就是讲gameObject拖过去,选择方法;

以下代码就是手动写了这个过程。

 1 using UnityEngine;
 2 using System.Collections;
 3 
 4 //事件的初始化
 5 public class EventTest : MonoBehaviour {
 6 
 7     Kettle kettle;
 8     void Awake()
 9     {
10         PrintLog printLog = new PrintLog();
11         kettle = new Kettle();
12         //传说中的事件订阅;就是手动设定一下,当事件触发的时候,执行的函数(printLog.Out)
13         kettle.Warning += new Kettle.myDelegate(printLog.Out);
14     }
15 
16     void Update()
17     {
18         if (Input.GetMouseButtonDown(0))
19         {
20             kettle.Begin();         
21         }
22     }
23 }
24 
25 //水壶烧水
26 public class Kettle
27 {
28     //定义委托
29     public delegate void myDelegate();
30     //定义该委托下的事件
31     public event myDelegate Warning;
32     //开始烧水,触发事件
33     public void Begin()
34     {
35         if (Warning != null)
36         {
37             Warning();
38         }
39     }
40 }
41 
42 //触发事件执行这个函数
43 public class PrintLog
44 {
45     public void Out()
46     {
47         Debug.LogWarning("+++++++++++");
48     }
49 }
原文地址:https://www.cnblogs.com/singledigit/p/5626121.html