假设我有一些代码,看起来像这样:
foreach(type x in list y)
{
//dostuff1(x)
}
foreach(type x in list y)
{
//dostuff2(x)
}
foreach(type x in list y)
{
//dostuff3(x)
}
foreach(type x in list y)
{
//dostuff4(x)
}
foreach(type x in list y)
{
//dostuff5(x)
}
我无法将事物组合成一个大的for循环,就像这样:
foreach (type x in list y)
{
//dostuff1(x)
//dostuff2(x)
//dostuff3(x)
//dostuff4(x)
//dostuff5(x)
}
这样做会改变顺序。对于如何使C#代码更简单的最佳方法有什么评论吗?
我想我可以通过创建像这样的函数来解决这个问题,虽然我宁愿让它保持原样,而不是强迫未来读者理解 yield
:
void func(type x)
{
dostuff1(x)
yield 0;
dostuff2(x)
yield 0;
dostuff3(x)
yield 0;
dostuff4(x)
yield 0;
dostuff5(x)
yield break;
}
for (int i = 0; i<5; ++i)
{
foreach (type x in list y)
{
//Call func(x) using yield semantics, which I'm not going to look up right now
}
}