我已经定义了以下扩展方法:
public static void ForEach<T>(this IEnumerable<T> sequence, Action<T> action)
{
foreach (T obj in sequence)
{
action(obj);
}
}
Run Code Online (Sandbox Code Playgroud)
然后我可以用它作为:
new [] {1, 2, 3} // an IEnumerable<T>
.ForEach(n =>
{
// do something
});
Run Code Online (Sandbox Code Playgroud)
我希望能够利用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
});
Run Code Online (Sandbox Code Playgroud)
可这些关键字仅在使用for,foreach,while或do-while循环?
这些关键字只能在for,foreach,while循环中使用吗?
是.这些语句仅限于循环类型.正如文档所说:
continue语句将控制权传递给封闭的while,do,for或foreach语句的下一次迭代.
而且:
break语句终止它出现的最近的封闭循环或switch语句.控制权将传递给终止语句后面的语句(如果有).
我建议你使用常规foreach,这是自我表达的原样.我认为任何在ForEach扩展方法中语义使用它们的尝试都会产生比使用常规循环更奇怪的代码.
我的意思是,这不简单吗?:
var arr = new [] {1, 2, 3}
foreach (int number in arr)
{
if(n == 1) { continue; }
if(n == -1) { break; }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
466 次 |
| 最近记录: |