C#事件的基础理解

事件基于委托,为其提供了一个发布/订阅机制。(事件是一种特殊签名的委托)

学习事件必须先学会委托,二者的第一个区别是,委托可以在局部声明变量,事件不可以。

namespace 事件{
	class Program{
		public delegate void MyDelegate();
		
		public event MyDelegate mydelegate;//事件只能在类的成员里声明委托变量
		static void Main(string[] args){
			Program p = new Program();
			p.mydelegate = Test1;
			p.mydelegate();
		}
		
		static void Test1(){
			Console.WriteLine("test1");
			Console.ReadyKey();
		}
	}
}

为更好的理解事件,学习设计模式——观察者模式。

namespace 观察者设计模式{
	class Cat{
		private string name;
		private string color;

		public Cat(string name,string color){
			this.name = name;
			this.color = color;
		}
		
		public void CatComing(){
			Console.WriteLine(color+"的猫"+name+"过来了,喵喵喵");

			if(catCome != null)
				catCome();//触发消息
		}

		public event Action catCome;//加完event后,事件不能在类的外部触发,只能在类的内部调用。发布消息
	}

	class Mouse{
		private string name;
		private string color;

		public Mouse(string name,string color,Cat cat){
			this.name = name;
			this.color = color;
			cat.catCome += this.RunAway;//注册方法:订阅消息
		}

		public void RunAway(){
			Console.WriteLine(color+"的老鼠"+name+"说:老猫来了");
		}
	}

	class Program{
		static void Main(string[] args){
			Cat cat = new Cat("加菲猫","黄色");
			Mouse mouse1 = new Mouse("米奇","黑色",cat);
			Mouse mouse2 = new Mouse("唐老鸭","黄色",cat);
			Mouse mouse3 = new Mouse("佩奇","粉红色",cat);
			cat.CatComing();
			Console.ReadyKey();
		}
	}
}

综上,我们明白事件和委托的第二个区别,事件不能在外部触发,只能在内部调用。

跟着C#里的Event事件,我们结合UnityEvent来实际应用。

UnityEvent可以让我们在编辑器面板上查看所有的订阅用户,从而订阅消息注册方法,当事件被触发时即实现方法回调。为了实现直接编辑事件绑定等操作,得使用Serializable。

Using UnityEngine;
Using UnityEngine.Events;

[System.Serializable]
public class IdolEvent : UnityEvents<string>{

}

public class Idol : MonoBehaviour{
	public IdolEvent idolEvent;

	private void Start(){
		if(idolEvent == null){
			idolEvent = new IdolEvent();	
		}
		idolEvent.Invoke("Idol give up writing.");
	}
}
Using UnityEngine;

public class SubcriberA : MonoBehaviour{
	public void LikeIdol(string idolAction){
		print(idolAction + "i will support u");
	}
}

Using UnityEngine;

public class SubcriberB : MonoBehaviour{
	public void HateIdol(string idolAction){
		print(idolAction + "i will hate u");
	}
}

当unity拖拽绑定后,实现基于delegate的Event同样的效果,如果直接在脚本里绑定,先理解二者的区别,UnityEvent是一个对象,通过AddListener()方法绑定。

Using UnityEngine;

public class SubcriberB : MonoBehaviour{
	public Idol myIdol;

	private void OnEnable(){
		myIdol.idoleEvent.AddListener(HateIdol);
	}

	private void OnDisable(){
		myIdol.idoleEvent.RemoveListener(HateIdol);
	}

	public void HateIdol(string idolAction){
		print(idolAction + "i will hate u");
	}
}

猜你喜欢

转载自blog.csdn.net/vrandi/article/details/81627095