.Net框架为事件定义了标准模式。他的目的是保持框架和用户代码之间的一致性标准事件模式的核心是System.EventArgs--------预定义的没有成员的框架类。
EventArgs是用于为事件传递信息的基类。
我们在unity中写个简单的例子,目录结构如下图
NameChangedEventArgs中的代码如下
public class NameChangedEventArgs {
public string LastName;
public string NewName;
public NameChangedEventArgs(string lastName,string newName) {
LastName = lastName;
NewName = newName;
}
}
可以看到我们想要在监听的事件发生的时候传回一个NameChangedEventArgs结构的参数
MethodEvent中的代码如下
public class MethodEvent {
//public event EventHandler<NameChangedEventArgs> DataChangeNotice;
public delegate void NameChangedEventHandler(object sender, NameChangedEventArgs e);
public event NameChangedEventHandler NameChanged;
private string name;
private string oldName;
private static MethodEvent Instance;
public static MethodEvent GetInstance(){
if (Instance == null) {
Instance = new MethodEvent();
}
return Instance;
}
public void OnNameChangedName(string name){
Debug.Log("MethodEvent SetName DataChangeNotice "+ nameChanged);
oldName = this.name;
this.name = name;
if (nameChanged != null) {
NameChanged(this,new NameChangedEventArgs(oldName, this.name));
}
}
}
在 .net框架中
public event EventHandler<NameChangedEventArgs> DataChangeNotice;
和
public delegate void NameChangedEventHandler(object sender, NameChangedEventArgs e);
public event NameChangedEventHandler nameChanged;
public event NameChangedEventHandler nameChanged;
表示的含义是一样的
EventHandler是.net定义的一个泛华委托
委托的名字必须以EventHandler结尾 就像这样
public delegate void NameChangedEventHandler(object sender, NameChangedEventArgs e);
方法名和事件名一致,以On作为开头
public void OnNameChangedName(string name){。。。}
下面是UIViewEvent中的代码
using UnityEngine;
using System.Collections;
public class UIViewEvent : MonoBehaviour {
private MethodEvent methodEvent;
// Use this for initialization
void Start () {
methodEvent = MethodEvent.GetInstance ();
methodEvent.NameChanged += DataChange;
}
// Update is called once per frame
void Update () {
}
public void DataChange(object sender, NameChangedEventArgs e) {
Debug.Log ("oldName "+e.LastName+" newName "+e.NewName);
}
void OnDestroy(){
methodEvent.NameChanged -= DataChange;
}
}
在这里我们只可以这样写
methodEvent.NameChanged += DataChange;
而不可以这样写
methodEvent.NameChanged = DataChange;
下面是TestEvent代码
using UnityEngine;
using System.Collections;
public class TestEvent : MonoBehaviour {
private MethodEvent methodEvent;
public string name;
// Use this for initialization
void Start () {
methodEvent = MethodEvent.GetInstance ();
}
public void SetName(){
methodEvent.OnNameChangedName(name);
}
}