C#イベントバス
7610 ワード
ネットブログやGithubのソースコードを参考にして、最後のコードは以下の通りです.
public interface IEventBus
{
void Suscribe(Type tevent, Action action);
void Suscribe(Type tevent, Action action);
void Suscribe(Type tevent, Action action);
void Suscribe(Type tevent, Action action);
void Suscribe(Type tevent, Action action);
void Suscribe(Type tevent, Action action);
void Suscribe(Type tevent, Action action);
void PostMessage(Type TEvent,params object[] args);
void UnSuscribe(Type tevent);
}
public class EventBus :IEventBus
{
private Dictionary> dict = new Dictionary>();
private static EventBus eventBus;
public static EventBus MyEventBus
{
get
{
if (eventBus == null)
{
eventBus = new EventBus();
}
return eventBus;
}
}
public void PostMessage(Type type,params object[] args)
{
List arr = dict[type];
foreach(EventArgs eventArgs in arr)
{
eventArgs.ActiveMethod.Invoke(eventArgs.EventHost, args);
}
}
public void Suscribe(Type tevent,Action action)
{
if (!dict.Keys.Contains(tevent))
{
dict[tevent] = new List();
}
dict[tevent].Add(new EventArgs()
{
EventHost = action.Target,
ActiveMethod = action.Method
});
}
public void Suscribe(Type tevent, Action action)
{
if (!dict.Keys.Contains(tevent))
{
dict[tevent] = new List();
}
dict[tevent].Add(new EventArgs()
{
EventHost = action.Target,
ActiveMethod = action.Method
});
}
public void Suscribe(Type tevent, Action action)
{
if (!dict.Keys.Contains(tevent))
{
dict[tevent] = new List();
}
dict[tevent].Add(new EventArgs()
{
EventHost = action.Target,
ActiveMethod = action.Method
});
}
public void Suscribe(Type tevent, Action action)
{
if (!dict.Keys.Contains(tevent))
{
dict[tevent] = new List();
}
dict[tevent].Add(new EventArgs()
{
EventHost = action.Target,
ActiveMethod = action.Method
});
}
public void Suscribe(Type tevent, Action action)
{
if (!dict.Keys.Contains(tevent))
{
dict[tevent] = new List();
}
dict[tevent].Add(new EventArgs()
{
EventHost = action.Target,
ActiveMethod = action.Method
});
}
public void Suscribe(Type tevent, Action action)
{
if (!dict.Keys.Contains(tevent))
{
dict[tevent] = new List();
}
dict[tevent].Add(new EventArgs()
{
EventHost = action.Target,
ActiveMethod = action.Method
});
}
public void Suscribe(Type tevent, Action action)
{
if (!dict.Keys.Contains(tevent))
{
dict[tevent] = new List();
}
dict[tevent].Add(new EventArgs()
{
EventHost = action.Target,
ActiveMethod = action.Method
});
}
public void UnSuscribe(Type tevent)
{
List arr = dict[tevent];
arr.Clear();
arr = null;
}
}
public class EventArgs
{
public object EventHost { get; set; }
public MethodInfo ActiveMethod { get; set; }
}