5

我试图理解这个代码片段:

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

如果这个if语句有不止一行代码(包括for循环和两个returns),为什么它没有花括号?

4

7 回答 7

9

代码等价于:

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

当没有大括号时,只有下一条语句是 if 的一部分。对于for循环,theif是下一条语句,因此所有内容都包含在其中。

于 2013-05-01T18:42:03.347 回答
6

if语句只有一行代码。底部return false; 在 if 语句之外。

于 2013-05-01T18:38:58.297 回答
5

如果这个 IF 语句多于一行代码

它没有。第一条if语句的正文只有:return false;. 其余的都是在if身体结束之后。

于 2013-05-01T18:38:20.547 回答
4

如果 If 语句中没有任何大括号,则在 If 语句下将只考虑一个语句。

在这个例子中,只会执行一条语句:“return false;”

于 2013-05-01T18:41:38.247 回答
3

在 C# 中,花括号是可选的,但仅适用于第一行代码。

这意味着如果语句没有大括号,则只会执行 if 条件(语句体)之后的代码行。其他所有内容都在语句主体之外,因此不会被执行。

同样适用于 if else:

if(SomeCompare())
return false;
else
return true;
于 2013-05-01T18:42:27.090 回答
2

this is the same as:

public bool DoThisJob(string job, int numberOfShifts)
{
    if (!String.IsNullOrEmpty(currentJob))
    {
      return false;
    }
    else
    {
        for (int i = 0; i < jobsICanDo.Length; i++)
            if (jobsICanDo[i] == job)
            {
                currentJob = job;
                this.shiftsToWork = numberOfShifts;
                shiftsWorked = 0;
                return true;
            }
        return false;
    }
}

the else simply isnt needed, because it won't get executed due to the return, if the if statement evaluates to true

于 2013-05-01T18:40:41.377 回答
1

That IF Statement has not more than one line of code. If other codes was for that IF statement, they never execute because the code always returns false at the very first line after the IF.

于 2013-05-01T18:39:49.480 回答