您当前的位置: 首页 >  c#

染指流年灬

暂无认证

  • 5浏览

    0关注

    194博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

C#自定义低耦合观察者模式

染指流年灬 发布时间:2020-05-16 21:01:07 ,浏览量:5

原本这里的代码用于unity,但是写法与任何unityAPI没关联,所以只要是c#语言的都可以用

用法:

  • 首先定义一个字符串常量,用于对某事件的意义进行标明,例如
    public static string showDebugDrawGo = "showDebugDrawGo";
  • 然后,在某个地方对这个事件进行监听
 MsgUtil.AddEventListener(MsgEvents.showDebugDrawGo, (o) =>
        {
        	//o是个object数组,如果长度不是0,需要里面数据的时候需要显示转换为自己所需要的类型
          	//to do what u want to do
        });
  • 最后,当这个事件被调起的时候,上述监听的内容就会被执行
//可以传若干个参数,当然需要装箱拆箱,会引起GC操作
//nowSurGo 会被传递到上面的o数组里面
MsgUtil.CallFunc(MsgEvents.showDebugDrawGo, nowSurGo );

将脚本复制到项目,按照上述过程进行使用即可达到目标效果

MsgUtil脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MsgUtil 
{
	class MsgStruct {
		public funcDelegate func;
		public int key;
	}
	private static Hashtable msg_function = new Hashtable();


    public delegate void funcDelegate(params object[] bc);
	public delegate bool boolDelegate();

	private static int count = 0;
	public static int total = 0;

    

    public static int AddEventListenerCall(string msg_type, funcDelegate func)
    {
        func();
        return AddEventListener(msg_type, func);
    }


    public static int AddEventListener(string msg_type, funcDelegate func) {
		int index = -1;
		if (msg_function.ContainsKey(msg_type) == true) {
			List funcArr2 = (List)msg_function[msg_type];
			for (int i = 0; i             
关注
打赏
1665909078
查看更多评论
0.0408s