我想根据值更新控件,例如:
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");或者使用switch语句完成,等等,例如,再执行20次。
是否可以将这些方法(OneOfTheListBoxes.Items.Add("send data")放入字典中,这样我只需要输入操作该方法的键,而不是遍历每个语句。
或者你能给我一个能让我做到这一点的实践吗?或者如何用更少的代码实现这一点?
发布于 2009-06-17 10:23:43
是的,你可以像这样把所有的列表框都放进字典里;
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);
}发布于 2009-06-17 10:24:49
好的。使用字典,键包含StringName,值包含列表框。然后使用:
myDict[StringName].Items.Add("send data")https://stackoverflow.com/questions/1006175
复制相似问题