如何将自定义参数传递给事件处理程序

时间:2016-05-31 17:09:08

标签: c# lambda event-handling

我有以下代码,它基于条件使用匿名(lambda)方法为某些对象分配或取消分配参数化事件处理程序:

{
    if (condition)

        foreach (var channel in dataSource.Channels)
        {
            channel.NewSamples += (s, vals) => AddSamples(channel.Index, vals);
        }
    }
    else
    {
        foreach (var channel in dataSource.Channels)
        {
            channel.NewSamples -= (s, vals) => AddSamples(channel.Index, vals);
        }

    }
}

private void AddSamples(int channelIndex, IEnumerable<int> samples)
{
    /// do work
}

我怀疑这不会正确取消订阅,所以我想将channel.Index作为参数传递给指定的处理程序,但我不知道该怎么做。

1 个答案:

答案 0 :(得分:1)

您可以按频道将处理程序存储在字典中,如下所示:

Dictionary<Channel, YourEventHandler> _handlers = new Dictionary<Channel, YourEventHandler>();

...

if (condition)
    foreach (var channel in dataSource.Channels)
    {
        if (!_handlers.ContainsKey(channel)) {
            YourEventHandler handler = (s, vals) => AddSamples(channel.Index, vals);
            channel.NewSamples += handler;
            _handlers[channel] = handler;
        }
    }
}
else
{
    foreach (var channel in dataSource.Channels)
    {
        if (_handlers.ContainsKey(channel)) {
             channel.NewSamples -= _handlers[channel];
             _handlers.Remove(channel);
        }
    }
}