Untitled
unknown
csharp
10 months ago
1.9 kB
5
Indexable
using System;
using System.Collections;
using System.Collections.Generic;
public static class Observer
{
public enum Key
{
A, B
}
static readonly Dictionary<Key, List<Action>> nonParamEvents;
static readonly Dictionary<Key, Dictionary<System.Type, IList>> paramEvents = new();
public static void Notify(Key key)
{
if (!nonParamEvents.ContainsKey(key))
{
return;
}
for (int i = 0; i < nonParamEvents[key].Count; i++)
{
nonParamEvents[key][i].Invoke();
}
}
public static void Notify<T>(Key key, T args)
{
if (!paramEvents.ContainsKey(key))
{
return;
}
var eventList = (List<Action<T>>)paramEvents[key][typeof(T)];
for (int i = 0; i < eventList.Count; i++)
{
eventList[i].Invoke(args);
}
}
public static void Listen(Key key, Action @event)
{
if (!nonParamEvents.ContainsKey(key))
{
nonParamEvents[key] = new();
}
nonParamEvents[key].Add(@event);
}
public static void Listen<T>(Key key, Action<T> @event)
{
if (!paramEvents.ContainsKey(key))
{
paramEvents[key] = new Dictionary<Type, IList>();
}
Type type = typeof(T);
if (!paramEvents[key].ContainsKey(type))
{
paramEvents[key][type] = new List<T>();
}
paramEvents[key][type].Add(@event);
}
}
public class Example
{
public void A()
{
Delegate x = new Action(A);
Observer.Listen(Observer.Key.A, A);
Observer.Notify(Observer.Key.A);
}
public void B((int, float) args)
{
Observer.Listen<(int, float)>(Observer.Key.B, B);
Observer.Notify(Observer.Key.B, (1, 2f));
}
}Editor is loading...
Leave a Comment