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

Pyr*_*mon 2 c# enums dynamic 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;
    }
Run Code Online (Sandbox Code Playgroud)

但我更喜欢有一种方法(我可以调用三次)看起来像:

private void PopulateListBox(ListBox ListBoxName, Enum EnumName)
{
    // ... code here!
}
Run Code Online (Sandbox Code Playgroud)

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

Kam*_*ski 5

您需要将枚举类型传递给您的方法

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

所以称之为:

PopulateListBox(lstThree,typeof(EnumThree));
Run Code Online (Sandbox Code Playgroud)