纳金网
标题:
C# 中的 Event 与 delegate 区别
[打印本页]
作者:
狂风大尉
时间:
2014-6-24 10:48
标题:
C# 中的 Event 与 delegate 区别
区别:
1. event 是 delegate实现的
2. event 的触发只能在所在声明类中调用
A.cs
using UnityEngine;
using System.Collections;
//委托的 方法声明
public delegate int fun();
public class A : MonoBehaviour {
public fun delegateFun;
public event fun eventFun;
//类外触发事件的 对外接口
public void CallEventFun ()
{
if(eventFun != null)
{
eventFun();
}
}
}
复制代码
CallA.cs
using UnityEngine;
using System.Collections;
public class CallA : MonoBehaviour {
void Start ()
{
A a = GameObject.Find("Main Camera").GetComponent<A>();
//类外添加 事件 的响应函数
a.eventFun += CallBackEvent;
a.eventFun += CallBackEvent1;
//类外添加 委托 的响应函数
a.delegateFun += CallBackDelegate;
a.delegateFun += CallBackDelegate1;
//Event 触发 不能 在类外 直接调用事件的触发
a.eventFun();
//上面的写法将 报错 error CS0070: The event `A.eventFun' can only appear on the left hand side of += or -= when used outside of the type `A'
//Event 触发 在外面触发需要 通过封装的方法进行间接触发 eventFun 如下代码
//a.CallEventFun ();
//委托可以直接在类外 触发调用
a.delegateFun();
}
//事件响应处理
int CallBackEvent()
{
Debug.Log ("callBackA");
return 2;
}
int CallBackEvent1()
{
Debug.Log ("callBackAA");
return 2;
}
//委托响应处理
int CallBackDelegate(){
Debug.Log ("delegateFun");
return 2;
}
int CallBackDelegate1(){
Debug.Log ("delegateFun1");
return 2;
}
}
复制代码
需要注意的是很多人认为 event 使用的 响应方法需要使用void 通过上面的测试 是不正确的。
作者:
hariboot
时间:
2014-6-24 17:43
不错,说的比较详细,但是最好说下具体适用环境
作者:
hyui
时间:
2014-6-24 17:52
Good to know!
作者:
wucnj
时间:
2014-6-25 09:10
感谢分享!!!
欢迎光临 纳金网 (http://go.narkii.com/club/)
Powered by Discuz! X2.5