首先实现的功能很简单,就是点击按钮,文本显示(内心吐槽:这么简单还自定义干嘛啊!!!当然是为了学习QAQ)
第一步:创建一个枚举类型(测试就写一个类型了)
public enum EventType
{
eventText
}
第二步:创建delegate类(用做泛型)
public delegate void EventCallBack();
public delegate void EventCallBack<T>(T arg1);
public delegate void EventCallBack<T,W>(T arg1,W arg2);
public delegate void EventCallBack<T,W,E>(T arg1, W arg2, E arg3);
public delegate void EventCallBack<T,W,E,R>(T arg1, W arg2, E arg3, R arg4);
public delegate void EventCallBack<T, W, E, R,Y>(T arg1, W arg2, E arg3, R arg4, Y arg5);
第三步(重点来了):定义一个事件中心,用来添加消息,移除消息,广播消息
public class EventCenten
{
private static Dictionary<EventType, Delegate> m_EventTable = new Dictionary<EventType, Delegate>();
//提取相同的代码段,使用Delegate就可以让方法通用(无论函数是否带参)
static void AddingListen(EventType eventType, Delegate callBack)
{
//如果类型已经存在(键相等)
if (!m_EventTable.ContainsKey(eventType))
{
m_EventTable.Add(eventType, null);
}
//获取该回掉函数
Delegate d = m_EventTable[eventType];
//判断委托对象(函数)是不是空值,类型是否一致(带一个参,还是两个或者更多)
if (d != null && d.GetType() != callBack.GetType())
{
throw new Exception(string.Format("尝试为事件{0}添加不同类型的委托,当前事件所对应的委托是{1},要添加的委托是{2}", eventType, d.GetType(), callBack.GetType()));
}
}
static void RemovingListen(EventType eventType, Delegate callBack)
{
if (m_EventTable.ContainsKey(eventType))
{
Delegate d = m_EventTable[eventType];
if (d == null)
{
throw new Exception(string.Format("移除监听错误:事件{0}没有对应的委托", eventType));
}
else if (d.GetType() != callBack.GetType())
{
throw new Exception(string.Format("移除监听错误:尝试为事件{0}移除不同的类型的委托,当前委托类型为{1},要移除的对象