如果我有一个嵌套在另一个循环中的for循环,我如何才能以最快的方式有效地从两个循环(内部和外部)中出来?
我不想必须使用布尔值然后必须说转到另一个方法,而只是在外部循环之后执行第一行代码。
有什么又快又好的方法呢?
我在想异常并不便宜/只应该在真正异常的情况下抛出等等。因此,从性能的角度来看,我不认为这个解决方案是好的。
我不认为利用。net中的新特性(anon方法)来做一些非常基础的事情是正确的。
如果我有一个嵌套在另一个循环中的for循环,我如何才能以最快的方式有效地从两个循环(内部和外部)中出来?
我不想必须使用布尔值然后必须说转到另一个方法,而只是在外部循环之后执行第一行代码。
有什么又快又好的方法呢?
我在想异常并不便宜/只应该在真正异常的情况下抛出等等。因此,从性能的角度来看,我不认为这个解决方案是好的。
我不认为利用。net中的新特性(anon方法)来做一些非常基础的事情是正确的。
当前回答
有时候,将代码抽象到它自己的函数中,而不是使用早期返回(早期返回是邪恶的:)
public void GetIndexOf(Transform transform, out int outX, out int outY)
{
outX = -1;
outY = -1;
for (int x = 0; x < Columns.Length; x++)
{
var column = Columns[x];
for (int y = 0; y < column.Transforms.Length; y++)
{
if(column.Transforms[y] == transform)
{
outX = x;
outY = y;
return;
}
}
}
}
其他回答
好吧,去吧,但那很难看,而且并不总是可能的。您还可以将循环放入方法(或anon-method)中,并使用return退出回主代码。
// goto
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 100; j++)
{
goto Foo; // yeuck!
}
}
Foo:
Console.WriteLine("Hi");
vs:
// anon-method
Action work = delegate
{
for (int x = 0; x < 100; x++)
{
for (int y = 0; y < 100; y++)
{
return; // exits anon-method
}
}
};
work(); // execute anon-method
Console.WriteLine("Hi");
注意,在c# 7中,我们应该得到“局部函数”,这(语法tbd等)意味着它应该像这样工作:
// local function (declared **inside** another method)
void Work()
{
for (int x = 0; x < 100; x++)
{
for (int y = 0; y < 100; y++)
{
return; // exits local function
}
}
};
Work(); // execute local function
Console.WriteLine("Hi");
最干净、最短、最可重用的方法是自调用匿名函数:
没有转到 没有标签 没有临时变量 没有命名函数
用匿名方法,比上面的答案短一行。
new Action(() =>
{
for (int x = 0; x < 100; x++)
{
for (int y = 0; y < 100; y++)
{
return; // exits self invoked lambda expression
}
}
})();
Console.WriteLine("Hi");
不要引用我的话,但你可以在MSDN中使用goto。还有其他解决方案,比如在两个循环的每次迭代中都检查一个标志。最后,您可以使用异常作为问题的重量级解决方案。
转到:
for ( int i = 0; i < 10; ++i ) {
for ( int j = 0; j < 10; ++j ) {
// code
if ( break_condition ) goto End;
// more code
}
}
End: ;
条件:
bool exit = false;
for ( int i = 0; i < 10 && !exit; ++i ) {
for ( int j = 0; j < 10 && !exit; ++j ) {
// code
if ( break_condition ) {
exit = true;
break; // or continue
}
// more code
}
}
例外:
try {
for ( int i = 0; i < 10 && !exit; ++i ) {
for ( int j = 0; j < 10 && !exit; ++j ) {
// code
if ( break_condition ) {
throw new Exception()
}
// more code
}
}
catch ( Exception e ) {}
自从几十年前我第一次看到C语言中的break,这个问题就一直困扰着我。我希望一些语言增强会有一个扩展打破,这样工作:
break; // our trusty friend, breaks out of current looping construct.
break 2; // breaks out of the current and it's parent looping construct.
break 3; // breaks out of 3 looping constructs.
break all; // totally decimates any looping constructs in force.
我认为除非你想做“布尔的事情”,否则唯一的解决方案实际上是抛出。你显然不应该这么做!