在我的几个项目中,我显然需要比标准.NET事件更强大的功能。
基本上,我想要在消息泵中选择,当他们感兴趣的组件发生变化时,将回调(事件)提升到特定订阅者。
这可能是一个项目的特定I / O更改状态(例如按钮关闭联系人),或者是从无线以太网接收的另一个特定MAC地址的消息。
我目前的想法是使用字典和每个地址的代表列表(对于此示例)。
我还没有调试过这个,但是右边是以下几行吗?
class CustomSubscription
{
public delegate void DataReceivedHandler(object sender, DataReceivedEventArgs args);
public class DataReceivedEventArgs : EventArgs
{
public byte[] data;
}
private readonly Dictionary<int, List<DataReceivedHandler>> _subscribers;
public CustomSubscription()
{
_subscribers = new Dictionary<int, List<DataReceivedHandler>>();
}
public void AddSubscriber(int address, DataReceivedHandler callback)
{
if (false == _subscribers.ContainsKey(address))
{
_subscribers.Add(address, new List<DataReceivedHandler>());
}
_subscribers[address].Add(callback);
}
public void RemoveSubscriber(int address, DataReceivedHandler callback)
{
if (false == _subscribers.ContainsKey(address))
{
return;
}
if (_subscribers[address].Contains(callback))
{
_subscribers[address].Remove(callback);
}
}
public void HandleIncommingData(int address, object sender, byte[] payload)
{
if (false == _subscribers.ContainsKey(address))
{
// Nothing subscribed - take no action
return;
}
// Raise callbacks with all subscribers
foreach (DataReceivedHandler callback in _subscribers[address])
{
callback(sender, new DataReceivedEventArgs
{
data = payload
});
}
}
}
答案 0 :(得分:0)
看起来您正在尝试实现事件聚合器模式。网上已经有很多实现。你可以从这里开始,例如: https://stackoverflow.com/questions/2343980/event-aggregator-implementation-sample-best-practices