C# 委托&事件

扫码查看

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

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

 using UnityEngine;
using System.Collections; //委托测试
public class Test : MonoBehaviour { /*定义委托
* 可以传递函数
* 相当于定义一个模板
* 符合模板的函数可以利用这个委托来使用
* */
delegate int Calculate(int _a, int _b); void Start ()
{
//创建委托,传入 Add 表示使用当前的委托相当于使用 Add 方法
Calculate c = new Calculate(Add); //使用委托
int d = c(, ); print(d);
} int Add(int _a, int _b)
{
return _a + _b;
} int Sub(int _a, int _b)
{
return _a - _b;
}
}

事件

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

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

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

 using UnityEngine;
using System.Collections; //事件的初始化
public class EventTest : MonoBehaviour { Kettle kettle;
void Awake()
{
PrintLog printLog = new PrintLog();
kettle = new Kettle();
//传说中的事件订阅;就是手动设定一下,当事件触发的时候,执行的函数(printLog.Out)
kettle.Warning += new Kettle.myDelegate(printLog.Out);
} void Update()
{
if (Input.GetMouseButtonDown())
{
kettle.Begin();
}
}
} //水壶烧水
public class Kettle
{
//定义委托
public delegate void myDelegate();
//定义该委托下的事件
public event myDelegate Warning;
//开始烧水,触发事件
public void Begin()
{
if (Warning != null)
{
Warning();
}
}
} //触发事件执行这个函数
public class PrintLog
{
public void Out()
{
Debug.LogWarning("+++++++++++");
}
}
05-07 09:27
查看更多