Elv*_*iel 5 c# if-statement curly-braces
我想了解这段代码:
class Worker
{
public bool DoThisJob(string job, int numberOfShifts)
{
if (!String.IsNullOrEmpty(currentJob))
return false;
for (int i = 0; i < jobsICanDo.Length; i++)
if (jobsICanDo[i] == job)
{
currentJob = job;
this.shiftsToWork = numberOfShifts;
shiftsWorked = 0;
return true;
}
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
如果这个if语句有多行代码(包括for循环和两个returns),为什么它没有花括号?
代码等同于:
class Worker
{
public bool DoThisJob(string job, int numberOfShifts)
{
if (!String.IsNullOrEmpty(currentJob))
{
return false;
}
for (int i = 0; i < jobsICanDo.Length; i++)
{
if (jobsICanDo[i] == job)
{
currentJob = job;
this.shiftsToWork = numberOfShifts;
shiftsWorked = 0;
return true;
}
}
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
当没有花括号时,只有下一个语句是if的一部分.对于for循环,它if是下一个语句,因此所有内容都包含在内.
该if语句只有一行代码.底部return false; 在if语句之外.