纳金网

标题: C# 中的 Event 与 delegate 区别 [打印本页]

作者: 狂风大尉    时间: 2014-6-24 10:48
标题: C# 中的 Event 与 delegate 区别
区别:
   1. event 是 delegate实现的
   2. event 的触发只能在所在声明类中调用

A.cs
  1. using UnityEngine;
  2. using System.Collections;

  3. //委托的 方法声明
  4. public delegate int fun();

  5. public class A : MonoBehaviour {

  6.         public fun delegateFun;

  7.         public event fun eventFun;  
  8.          
  9.         //类外触发事件的 对外接口
  10.         public void CallEventFun ()
  11.         {
  12.                 if(eventFun != null)
  13.                 {
  14.                         eventFun();
  15.                 }
  16.         }  
  17. }
复制代码
CallA.cs
  1. using UnityEngine;
  2. using System.Collections;

  3. public class CallA : MonoBehaviour {
  4.    
  5.         void Start ()
  6.         {
  7.                 A a = GameObject.Find("Main Camera").GetComponent<A>();  
  8.                 //类外添加 事件 的响应函数
  9.                 a.eventFun += CallBackEvent;
  10.                 a.eventFun += CallBackEvent1;

  11.                 //类外添加 委托 的响应函数
  12.                 a.delegateFun += CallBackDelegate;
  13.                 a.delegateFun += CallBackDelegate1;


  14.                 //Event 触发 不能 在类外 直接调用事件的触发   
  15.                 a.eventFun();
  16.                 //上面的写法将 报错  error CS0070: The event `A.eventFun' can only appear on the left hand side of += or -= when used outside of the type `A'

  17.                 //Event 触发  在外面触发需要 通过封装的方法进行间接触发 eventFun 如下代码
  18.                 //a.CallEventFun ();


  19.                 //委托可以直接在类外 触发调用
  20.                 a.delegateFun();
  21.         }

  22.         //事件响应处理
  23.         int CallBackEvent()
  24.         {
  25.                 Debug.Log ("callBackA");
  26.                 return 2;
  27.         }
  28.         int CallBackEvent1()
  29.         {
  30.                 Debug.Log ("callBackAA");
  31.                 return 2;
  32.         }


  33.         //委托响应处理
  34.         int CallBackDelegate(){
  35.                 Debug.Log ("delegateFun");
  36.                 return 2;
  37.         }

  38.         int CallBackDelegate1(){
  39.                 Debug.Log ("delegateFun1");  
  40.                 return 2;
  41.         }




  42. }
复制代码
需要注意的是很多人认为  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