我想基于一个值更新控件,例如:
if (StringName == StringName2)
ListBox1.Items.Add("send data");
else if (StringName3 == StringName4)
DifferentListBox.Items.Add("send data");
else if (StringName5 == StringName3)
AnotherListBox.Items.Add("send data");
Run Code Online (Sandbox Code Playgroud)
或者使用switch语句等完成另外20次,例如.
是否可以将这些方法(OneOfTheListBoxes.Items.Add("send data")放在字典中,所以我只需要输入键来操作方法而不是遍历每个语句.
或者你能指点一下让我实现这一目标的练习吗?或者如何用更少的代码实现这一目标?
是的,您可以将所有列表框放入字典中;
Dictionary<string, ListBox> _Dictionary;
public Something() //constructor
{
_Dictionary= new Dictionary<string, ListBox>();
_Dictionary.add("stringname1", ListBox1);
_Dictionary.add("stringname2", ListBox2);
_Dictionary.add("stringname3", ListBox3);
}
....
public void AddToListBox(string listBoxName, string valueToAdd)
{
var listBox = _Dictionary[listBoxName];
listBox.Items.Add(valueToAdd);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
771 次 |
| 最近记录: |