gpt4 book ai didi

c# - 如何在扩展方法中使用 'continue' 和 `break`?

转载 作者:太空狗 更新时间:2023-10-30 00:14:13 24 4
gpt4 key购买 nike

我定义了以下扩展方法:

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
});

我希望能够在我的扩展方法中利用 continuebreak 以便我可以:

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
});

这些关键字只能在 forforeachwhiledo-while 循环中使用吗?

最佳答案

Can these keywords only be used within a for, foreach, while loops?

是的。这些语句仅限于循环类型。 As the docs say :

The continue statement passes control to the next iteration of the enclosing while, do, for, or foreach statement in which it appears.

And :

The break statement terminates the closest enclosing loop or switch statement in which it appears. Control is passed to the statement that follows the terminated statement, if any.

我建议您使用常规的 foreach,它是 self 表达的。我认为任何在 ForEach 扩展方法中语义使用它们的尝试都会导致比使用常规循环更奇怪的代码。

我的意思是,这不是更简单吗?:

var arr = new [] {1, 2, 3}
foreach (int number in arr)
{
if(n == 1) { continue; }
if(n == -1) { break; }
}

关于c# - 如何在扩展方法中使用 'continue' 和 `break`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31454925/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com