【发布时间】:2015-07-16 13:01:29
【问题描述】:
我定义了如下扩展方法:
public static void ForEach<T>(this IEnumerable<T> sequence, Action<T> action)
{
foreach (T obj in sequence)
{
action(obj);
}
}
然后我可以将其用作:
new [] {1, 2, 3} // an IEnumerable<T>
.ForEach(n =>
{
// do something
});
我希望能够在我的扩展方法中利用continue 和break,这样我就可以做到:
new [] {1, 2, 3}
.ForEach(n =>
{
// this is an overly simplified example
// the n==1 can be any conditional statement
// I know in this case I could have just used .Where
if(n == 1) { continue; }
if(n == -1) { break; }
// do something
});
这些关键字只能在for、foreach、while 或do-while 循环中使用吗?
【问题讨论】:
-
恕我直言,这种扩展方法根本没有意义。它只会使您的代码复杂化。为什么不使用
foreach循环?您不必用扩展方法替换所有内容。 -
@Daniel - 我不同意,我是函数式编程
linq和morelinq的忠实粉丝,在我看来(以及我团队中许多其他人的意见)这太多了比其他方法更容易阅读。 -
对于每个已经在列表 fyi 上
-
但不在 IEnumerable 上 ;-) 因此它在
MoreLinq中可用