-1

编程和阅读如何预订的新手。问题是关于循环的。我有以下代码:

public bool DoThisJob(string job, int numShift) {
        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;

如果 currentJob 字符串不为空则返回 false 还是返回 true?没有其他声明,所以如果它是真的,我们怎么知道该怎么做?

接下来运行一个for循环,然后for循环再次运行,因为它返回false或true?最后运行一个不言自明的 if 语句。

4

5 回答 5

1

由于“return”声明,没有其他内容。它立即中止函数的执行并返回到调用函数。你可以用 else 来写它,它的功能是一样的。

于 2013-01-25T15:06:30.107 回答
0

如果 currentJob 字符串为空,则该if语句将不会运行,它将进入for循环。

如果for循环中的条件触发它返回 true,则该方法返回 true,并且永远不会达到最后一次返回。

如果for循环没有返回 true,它将落到最后一行,并且该方法将返回 false。

于 2013-01-25T15:07:07.657 回答
0

return 语句在该点停止函数的执行并将控制权返回给调用过程。

public bool DoThisJob(string job, int numShift) {
        if (!string.IsNullOrEmpty(currentJob))
            return false; // If it is not empty then function call returns from this statement

        // Else, flow control falls through and below code is executed
        for (int i = 0; i < jobsICanDo.Length; i++) {
            if (jobsICanDo[i] == job) {
                currentJob = job;
                this.shiftsToWork = numberOfShifts;
                shiftsWorked = 0;
                return true;
            }

        return false;
        }

我希望,这可以澄清这个问题。

于 2013-01-25T15:09:33.987 回答
0

There is no else statement so how do we know what to do if it is true?.

if ... else(或经典称为if .. then .. else)构造else中,如果是可选的,并且在它不存在的情况下,它将落入if块外的下一个语句,在这种情况下,它的for语句

您的上述功能可以等效地类似于

public bool DoThisJob(string job, int numShift) {
        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;
        }
于 2013-01-25T15:05:40.517 回答
0

您的功能可以简化如下,无需循环;

public bool DoThisJob(string job, int numShift) {

    if (!string.IsNullOrEmpty(currentJob) || !jobsICanDo.Contains<string>(job))
    {
       //if currentJob NOT null/empty OR 
       //job is not in the jobsICanDo[] array
       return false;
    }
    else
    {
        currentJob = job;
        this.shiftsToWork = numberOfShifts;
        shiftsWorked = 0;
        return true;
    }
}
于 2013-01-25T15:21:27.760 回答