将方法作为参数传递给另一个方法

时间:2013-03-18 11:08:48

标签: c# .net winforms combobox selectedindexchanged

我正在widows c#.net中开发项目。在形式上我有超过8个组合框控制。 当combobox1选择改变如下时,我将数据加载到combobox2。

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
     comboBox2.DataSource = DataTable;
     comboBox2.DisplayMember="Name";
     comboBox2.ValueMember = "ID";
}

当我选择如下的combobox2时,将加载Combobox3。

 private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
 {
     comboBox3.DataSource = DataTable;
     comboBox3.DisplayMember = "Age";
     comboBox3.ValueMember = "AgeCode";
 }

就像我将数据加载到组合框的其余部分一样 这里的问题是错误将发生,如果我没有检查comboBox1_SelectedIndexChanged方法是否加载comboBox2。

我知道我们可以通过使用布尔变量检查这个,但可怕的是我们需要保持其“真/假”状态以便所有方法休息。

所以我想以简单的方式解决这个问题,我会使用Add(combobox, Methodname)方法和Remove(combobox, method)方法在组合框comboBox_SelectedIndexChanged中添加和删除SelectedIndexChanged函数事件。

但是我无法将该方法作为参数传递。任何人都可以告诉我如何将方法作为参数传递给我。

3 个答案:

答案 0 :(得分:3)

methodAdd方法中的Remove参数如果您的意思是comboBox1_SelectedIndexChanged和/或comboBox2_SelectedIndexChanged,那么解决方案就是

private void Add(ListControl dropDownList, EventHandler handlerMethodName)
{
   dropDownList.OnSelectedIndexChanged += handlerMethodName;
   //some logic here
}

private void Remove(ListControl dropDownList, EventHandler handlerMethodName)
{
   dropDownList.OnSelectedIndexChanged -= handlerMethodName;
   //some logic here
}

请注意:DropDownList ASP.NETComboBox适用于WinForms个应用。

有关详情,请参阅:MSDN - DropDownListMSDN - ListControl.SelectedIndexChanged Event

答案 1 :(得分:1)

我不确定你要做什么。但为什么不是ComboBox和方法的字典?

像这样:

var dict = Dictionary<ComboBox, Action<object, EventArgs>>();

private void Add(ComboBox c, Action<object, EventArgs>e) {
   dict[c] = e;
}

private void Remove(ComboBox c, Action<object, EventArgs> e) {
   dict.Remove(c);
}

并致电::

private void CallHandler(ComboBox c, EventArgs e)
{
   dict[c](c, e);
}

可选地

private void AddHandler(ComboBox c, Action<object, EventArgs> e)
{
   c.SelectedIndexChanged += e;
}

private void RemoveHandler(ComboBox c, Action<object, EventArgs> e)
{
   c.SelectedIndexChanged -= e;
}

答案 2 :(得分:1)

我也不是100%确定您正在寻找的那种解决方案,但我对您的需求的理解是以下方法:

public void Add(DropDownList combo, EventHandler method)
{
    combo.SelectedIndexChanged += method;
}

public void Remove(DropDownList combo, EventHandler method)
{
    combo.SelectedIndexChanged -= method;
}

现在,您可以定义自己的方法,该方法应与EventHandler委托具有相同的签名:

public void MyMethod1(object sender, EventArgs e)
{}

您可以通过调用上面定义的方法注册和取消注册您的方法:

DropDownList lst = new DropDownList();
Add(lst, MyMethod1);
Remove(lst, MyMethod1);

但请注意,这可能不是您问题的最佳解决方案。

相关问题