c# 委托

来源:互联网 发布:mysql压缩包安装教程 编辑:程序博客网 时间:2024/05/16 08:24

委托将方法调用者和目标方法动态关联起来

我们可以这样来定义一个委托

delegate int Transformer(int x);

定义委托的关键字是delegate

我们可以这么来使用

int Square(int x){ return x*x;}

Transformer t = Square;

int answer = t(3);


我们在unity中写个简单的例子来看一下委托的使用方法

假设我们有一个字段为name,当name发生改变的时候相应的UI层要监听到这个改变,这时候我们就可以使用委托

代码的目录结构如下图


我们在MethodDelegate中定义一个字段name,TestDelegate中去改变这个字段,UIView中监听到这个字段被改变了


MethodDelegate中的代码如下

using UnityEngine;using System.Collections;public class MethodDelegate{public delegate void DataChange();public DataChange DataChangeNotice;private string name;private static MethodDelegate Instance;public static MethodDelegate GetInstance(){if (Instance == null) {Instance = new MethodDelegate();}return Instance; }public void SetName(string name){this.name = name;if (DataChangeNotice != null) {DataChangeNotice();        }}}

TestDelegate中的代码如下

using UnityEngine;using System.Collections;public class TestDelegate : MonoBehaviour {private MethodDelegate methodDelegate;public string name;// Use this for initializationvoid Start () {methodDelegate = MethodDelegate.GetInstance ();}public void SetName(){methodDelegate.SetName (name);}}

UIView中的代码如下

using UnityEngine;using System.Collections;public class UIView : MonoBehaviour {private MethodDelegate methodDelegate;// Use this for initializationvoid Start () {methodDelegate = MethodDelegate.GetInstance ();methodDelegate.DataChangeNotice += DataChange;}// Update is called once per framevoid Update () {}public void DataChange(){Debug.Log (" UIView DataChange");}void OnDestroy(){methodDelegate.DataChangeNotice -= DataChange;}}

在unity中创建一个button按钮

然后把TestDelegate和UIView脚本挂在Canvas上,给button按钮添加响应事件,事件函数为TestDelegate中的SetName方法,点击按钮我们就可以看到UIView中的DataChange函数被调用了。


委托的弊端

委托不禁可以使用 += 操作还可以使用=cao'z






0 0