【发布时间】:2012-05-02 14:18:00
【问题描述】:
我有以下函数,但它很长,很脏,我想优化它:
//some code
if (use_option1 == true)
{
foreach (ListViewItem item in listView1)
{
//1. get subitems into a List<string>
//
//2. process the result using many lines of code
}
}
else if (use_option2 = true)
{
//1. get a string from another List<string>
//
//2. process the result using many lines of code
}
else
{
//1. get a string from another List<string> (2)
//
//2. process the result using many lines of code
}
这很好用,但是很脏 我想用这样的东西:
//some code
if (use_option1 == true)
{
List<string> result = get_item();//get subitems into a List<string>
}
else if (use_option2 = true)
{
//get a string from another List<string>
}
else
{
//get a string from another List<string> (2)
}
//process the result using many lines of code
private void get_item()
{
//foreach bla bla
}
我应该如何让 get_item 函数每次都获取列表中的下一个项目?
我读过一些关于 GetEnumerator 的文章,但我不知道这是否是我的问题的解决方案或如何使用它。
【问题讨论】:
-
每个选项的处理代码是否相似?
-
在第一个代码段中,这个“//2. 多行代码处理结果”注释,是不是同一个过程?
-
是的,它是一样的,但我不能在函数中使用它,因为从一开始就有代码(//一些代码)。所以唯一的选择是使用 void 中的 foreach
-
提示:在 Visual Studio 中选择一段代码,点击“Refactor..Extract Method”,它会自动将该代码移动到一个方法中,并传递适当的参数。在某些情况下它不起作用 - 所以你需要更多地了解你在做什么,这总是好的。
-
ShaMora:正如我所说,您需要更好地理解您的代码。如果您尝试手动将部分代码提取到方法中会更好。
标签: c# loops foreach ienumerable enumerator