如何在C#中避免使用枚举重复代码?

时间:2013-10-10 10:57:55

标签: c# dynamic enums repeat

我使用三个相应枚举的值填充三个列表框。有没有办法避免使用三种独立但非常相似的方法?这就是我现在所拥有的:

    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!
}

我是一个没有经验的程序员,所以虽然我做了搜索,但我不太确定我在搜索什么。如果以前已经回答过,请道歉;我同样很感激能够得到现有答案。谢谢!

3 个答案:

答案 0 :(得分: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));

答案 1 :(得分: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);

答案 2 :(得分: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;
    }
相关问题