2009-06-17 45 views
0

我想更新基於值e.g控制:C#編程實踐

 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")置於 在字典中,所以我只需要輸入密鑰來操作該方法,而不是遍歷每個語句。

或者你可以指點我的做法,會讓我做到這一點?或者如何在更少的代碼中實現這一點?

+0

是否有意讓您比較不同的字符串,例如: (StringName == StringName2)與(StringName3 == StringName4)?這對解決方案有很大的不同。 – 2009-06-17 10:31:19

回答

7

是的,你可以把所有的列表框放到字典中,像這樣;

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); 
} 
+0

該死的!你擊敗了我... + 1 – Pondidum 2009-06-17 10:26:13

+0

Kirschstein有一個很好的解決方案。如果annakata的(下面)點是有效的:對不同的字符串進行測試,只要存在1:*字符串:ListBox關係,您仍然可以使用此解決方案,只需在Dictionary中多次輸入列表框。 例如, _Dictionary.Add(「string1」,ListBox1); _Dictionary.Add(「string2」,ListBox1); – Mark 2009-06-17 10:29:16

1

當然。使用帶有持有StringName的鍵的字典,並使用持有Listbox的值。 Then use:

myDict[StringName].Items.Add("send data")