我想创建一个带有命名事件的简单事件聚合器,例如:
Hub.AddListener(string Name, Action<int> Callback);
Hub.Invoke(string Name, int Message);
但是我无法找到使用委托,事件和字典的解决方案,Dictionary<string, EventHandler>
和Dictionary<string, Action<int>>
都不允许+=
更多订阅者加入同一事件。
那么我应该使用类似Dictionary<string, List<object>>
和副步骤事件/委托的东西吗?
答案 0 :(得分:2)
您想要的是多播代理:
public class Hub
{
private Dictionary<string, Action<int>> _events = new Dictionary<string, Action<int>>();
public void AddListener(string name, Action<int> callback)
{
if (!_events.ContainsKey(name))
_events.Add(name, callback);
else
{
var handler = _events[name];
_events[name] = handler + callback;
}
}
public void Invoke(string name, int message)
{
if (_events.ContainsKey(name))
{
var handler = _events[name];
handler(message);
}
}
}
样本用法:
Hub hub = new Hub();
hub.AddListener("one", delegate (int a) { Console.WriteLine("First " + a); });
hub.AddListener("one", delegate (int a) { Console.WriteLine("Second " + a); });
hub.Invoke("one", 5);
输出:
First 5
Second 5
您可以在此处详细了解:
How to: Combine Delegates (Multicast Delegates)(C# Programming Guide)