我正在用三个相应枚举的值填充三个列表框。有什么方法可以避免使用三种独立但非常相似的方法吗?这是我现在拥有的:
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!
}
我是一个缺乏经验的程序员,所以尽管我进行了搜索,但我不太确定我在搜索什么。如果之前已经回答过这个问题,我们深表歉意;我同样很高兴能看到一个现有的答案。谢谢!
最佳答案
您需要将枚举类型传递给您的方法
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));
关于c# - 如何避免在 C# 中使用枚举重复代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19293925/