没有括号的for循环的语法?

Tho*_*mas 6 c# syntax

for (int y = 0; y < GameBoard.GameBoardHeight; y++)
        for (int x = 0; x < GameBoard.GameBoardWidth; x++)
        {
            if (GetSquare(x, y) == "Empty")
            {
                 RandomPiece(x, y);
            }
        }
Run Code Online (Sandbox Code Playgroud)

第一个for循环没有大括号,下一行甚至不是带有a的语句;.这只是一个for循环.

怎么了?

Yog*_*esh 7

MSDN:for循环重复执行语句或语句块,直到指定的表达式求值为false.

要理解的要点是执行语句或语句块部分.嵌套for在您的示例中的是一个语句,由于该{ }对,它包含一个语句块.

因此,如果您将上述内容编写为每个嵌套操作只有一个语句,您将编写:

for (int y = 0; y < GameBoard.GameBoardHeight; y++)
    for (int x = 0; x < GameBoard.GameBoardWidth; x++)
        if (GetSquare(x, y) == "Empty")
            RandomPiece(x, y);
Run Code Online (Sandbox Code Playgroud)

或者作为每个嵌套操作的块语句:

for (int y = 0; y < GameBoard.GameBoardHeight; y++)
{
    for (int x = 0; x < GameBoard.GameBoardWidth; x++)
    {
        if (GetSquare(x, y) == "Empty")
        {
            RandomPiece(x, y);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Ria*_*Ria 3

将要迭代的语句括在花括号中。如果循环中只应包含一条语句,则可以省略花括号。

即使语句体仅包含单个语句,也应始终使用 if、for 或 while 语句的左大括号和右大括号。

大括号提高了代码的一致性和可读性。更重要的是,当将附加语句插入仅包含单个语句的主体时,很容易忘记添加大括号,因为缩进为结构提供了强有力的(但具有误导性的)指导。

for(int i = 0; i < 10; ++i) { Console.WriteLine(i) }
Run Code Online (Sandbox Code Playgroud)

注意:循环之后。如果没有大括号,则只有紧跟在 for 循环语句之后的第一条语句才会在循环中。

有关更多信息,请参阅:http://www.dotnetperls.com/omit-curly-brackets