2013-10-10 51 views
2

我用三個相應的枚舉值填充三個列表框。有沒有辦法避免有三種獨立但非常相似的方法?這是我現在有:如何避免使用C#中的枚舉重複代碼?

private void PopulateListBoxOne() 
    { 
     foreach (EnumOne one in Enum.GetValues(typeof(EnumOne))) 
     { 
      lstOne.Items.Add(one); 
     } 
     lstOne.SelectedIndex   = 0; 
    } 

    private void PopulateListBoxTwo() 
    { 
     foreach (EnumTwo two in Enum.GetValues(typeof(EnumTwo))) 
     { 
      lstTwo.Items.Add(two); 
     } 
     lstTwo.SelectedIndex   = 0; 
    } 

    private void PopulateListBoxThree() 
    { 
     foreach (EnumThree three in Enum.GetValues(typeof(EnumThree))) 
     { 
      lstThree.Items.Add(three); 
     } 
     lstThree.SelectedIndex   = 0; 
    } 

但是我反而更喜歡有一個方法(我可以調用三次)看起來像:

private void PopulateListBox(ListBox ListBoxName, Enum EnumName) 
{ 
    // ... code here! 
} 

我非常缺乏經驗的程序員,所以雖然我搜索了,但我並不確定我在尋找什麼。如果之前已經回答過,請道歉;我會同樣感謝被展示的現有答案。謝謝!

+0

Wudzik的答案制定權開箱。謝謝 - 我的堆棧溢出經驗的一個美麗的開始! (感謝其他答案,儘管我還沒有嘗試過)。 – Pyraemon

回答

5

您需要枚舉類型傳遞給你的方法

private void PopulateListBox(ListBox ListBoxName, Type EnumType) 
{ 
    foreach (var value in Enum.GetValues(EnumType)) 
    { 
     ListBoxName.Items.Add(value); 
    } 
    ListBoxName.SelectedIndex=0; 
} 

所以這樣稱呼它:

PopulateListBox(lstThree,typeof(EnumThree)); 
0

你可以嘗試像

private List<T> PopulateList<T>() 
    { 
     List<T> list = new List<T>(); 
     foreach (T e in Enum.GetValues(typeof(T))) 
     { 
      list.Add(e); 
     } 
     return list; 
    } 
3

你可以使用一個通用的方法:

private void PopulateListBox<TEnum>(ListBox listBox, bool clearBeforeFill, int selIndex) where TEnum : struct, IConvertible 
{ 
    if (!typeof(TEnum).IsEnum) 
     throw new ArgumentException("T must be an enum type"); 

    if(clearBeforeFill) listBox.Items.Clear(); 
    listBox.Items.AddRange(Enum.GetNames(typeof(TEnum))); // or listBox.Items.AddRange(Enum.GetValues(typeof(TEnum)).Cast<object>().ToArray()); 

    if(selIndex >= listBox.Items.Count) 
     throw new ArgumentException("SelectedIndex must be lower than ListBox.Items.Count"); 

    listBox.SelectedIndex = selIndex; 
} 

你如何使用它:

PopulateListBox<EnumThree>(lstThree, true, 0); 
+0

用於檢查泛型類型是Enum – wudzik