在一个方法中添加和删除事件,c#

时间:2016-04-08 22:32:19

标签: c# events

有时我需要在一堆控件中添加和删除事件。我总是通过一种添加事件的方法来做到这一点:

private void AddEvents(){
    textBox.TextChanged += TextChanged;
    integerUpDown.ValueChanged += ValueChanged;
    colorPicker.SelectedColorChanged += ColorChanged;
    //... and so on
}

同样用于移除事件:

private void RemoveEvents(){
    textBox.TextChanged -= TextChanged;
    integerUpDown.ValueChanged -= ValueChanged;
    colorPicker.SelectedColorChanged -= ColorChanged;
    //... and so on
}

我使用不同类型的控件和不同类型的EventArgs。我想将其压缩为一种方法,例如:

private void RemoveEvents(bool add){
    textBox.TextChanged add ? += : -= TextChanged;
    integerUpDown.ValueChanged add ? += : -= ValueChanged;
    //or method approach
    ManageEvent(colorPicker.SelectedColorChanged, ColorChanged, add);
    //... and so on
}

但这不可能吗?运营商。有办法吗?

3 个答案:

答案 0 :(得分:1)

条件操作根据语句的结果返回一个值。返回" + ="绝对无效,因为您基本上订阅了该活动。 https://msdn.microsoft.com/en-us/library/ty67wk28.aspx

但是,为什么不采取更简单的方法呢?

private void AddOrRemoveEvents(bool add)
{
    if (add)
    {
        AddEvents();
    }
    else 
    {
        RemoveEvents();
    }
}

答案 1 :(得分:1)

一行如果声明救援!会有一点点的重复,但也就是一个单线

if (add) textbox.TextChanged += TextChanged; else textbox.TextChanged -= TextChanged;

答案 2 :(得分:1)

我认为这很整洁。

首先,定义以下接口和类:

public interface IEventHolder
{
    void Attach();
    void Detach();
}

public class EventHolder<H> : IEventHolder
{
    private Action<H> _add;
    private Action<H> _remove;
    private H _handler;

    public EventHolder(Action<H> add, Action<H> remove, H handler)
    {
        _add = add;
        _remove = remove;
        _handler = handler;
    }

    public void Attach() { _add(_handler); }

    public void Detach() { _remove(_handler); }
}

现在您可以定义此私有字段:

    private List<IEventHolder> _eventHolders = new List<IEventHolder>();

Form_Load事件中,我已编写此代码:

    private void Form1_Load(object sender, EventArgs e)
    {
        _eventHolders.Add(new EventHolder<EventHandler>(h => textBox1.TextChanged += h, h => textBox1.TextChanged -= h, textBox1_TextChanged));
        _eventHolders.Add(new EventHolder<EventHandler>(h => numericUpDown1.ValueChanged += h, h => numericUpDown1.ValueChanged -= h, numericUpDown1_ValueChanged));
        _eventHolders.Add(new EventHolder<MouseEventHandler>(h => textBox2.MouseMove += h, h => textBox2.MouseMove -= h, textBox2_MouseMove));

        _eventHolders.ForEach(eh => eh.Attach());
    }

请注意,_eventHolders.ForEach(eh => eh.Attach());行会附加所有事件。

我的处理程序看起来像这样:

    private void textBox1_TextChanged(object sender, EventArgs e)
    { }

    private void numericUpDown1_ValueChanged(object sender, EventArgs e)
    {
        this.textBox1.Text = numericUpDown1.Value.ToString();
    }

    private void textBox2_MouseMove(object sender, MouseEventArgs e)
    {
        _eventHolders.ForEach(eh => eh.Detach());
    }

textBox2_MouseMove处理程序一次性分离所有事件。

我已经对此进行了测试,它就像一种享受。