6、 语句
6.1 每行一个语句
每行最多包含一个语句。如:
a++; //推荐
b--; //推荐 a++; b--; //不推荐
6.2 复合语句
复合语句是指包含\父语句{子语句;子语句;}\的语句,使用复合语句应遵循以下几点:
1 子语句要缩进。
2 左花括号“{” 在复合语句父语句的下一行并与之对齐,单独成行。 3 即使只有一条子语句要不要省略花括号“ {}”。 如
while (d + = s++)
{
n++; }
6.3 return 语句
return语句中不使用括号,除非它能使返回值更加清晰。如:
return;
return myDisk.size();
return (size ? size : defaultSize);
6.4 if、 if-else、if else-if 语句
if、 if-else、if else-if 语句使用格式:
if (condition)
{
statements;
}
if (condition) {
statements; } else {
statements; }
if (condition) {
statements; }
else if (condition) {
statements; } else {
statements; }
6.5 for、foreach 语句
for 语句使用格式:
for (initialization; condition; update)
{
statements; }
空的 for 语句(所有的操作都在initialization、condition 或 update中实现)使用格式
for (initialization; condition; update); // update user id
foreach 语句使用格式:
foreach (object obj in array)
{
statements;
}
注意: 1在循环过程中不要修改循环计数器。 2对每个空循环体给出确认性注释。
6.6 while 语句
while 语句使用格式:
while (condition)
{
statements; }
空的 while 语句使用格式:
while (condition);
6.7 do - while 语句
do - while 语句使用格式:
do
{
statements; } while (condition);
6.8 switch - case 语句
switch - case 语句使用格式:
switch (condition)
{
case 1:
statements; break; case 2: statements; break; default: statements; break; }
注意:
1、语句switch中的每个case各占一行。 2、语句switch中的case按字母顺序排列。 3、为所有switch语句提供default分支。
4、所有的非空 case 语句必须用 break; 语句结束。
6.9 try - catch 语句
try - catch 语句使用格式:
try
{
statements; }
catch (ExceptionClass e) {
statements; } finally {
statements; }
6.10 using 块语句
using
块语句使用格式:
using (object)
{
statements; }
6.11 goto 语句
goto 语句使用格式:
goto Label1:
statements; Lable1: statements;