返回语法有点奇怪

时间:2018-02-28 13:15:08

标签: c# return

经过几年的HTML / ASP后,我回到了C#编程。 我遇到过这些问题并且找不到它的作用。 这是一个类中的方法:

private string PeekNext()
{
    if (pos < 0)
        // pos < 0 indicates that there are no more tokens
        return null;
    if (pos < tokens.Length)
    {
        if (tokens[pos].Length == 0)
        {
            ++pos;
            return PeekNext();
        }
        return tokens[pos];
    }
    string line = reader.ReadLine();
    if (line == null)
    {
        // There is no more data to read
        pos = -1;
        return null;
    }
    // Split the line that was read on white space characters
    tokens = line.Split(null);
    pos = 0;
    return PeekNext();
}

在其他一些返回发生之前,它是否在调用自己?

这里发生了什么,从来没有看到一种方法回归自己!? 返回什么,空字符串或什么......? 或许我以前就错过了它。

也许很简单,但让我感到困惑。

2 个答案:

答案 0 :(得分:0)

private string PeekNext()
    {
        if (pos < 0)
            // pos < 0 indicates that there are no more tokens
            return null;
        if (pos < tokens.Length)
        {
            if (tokens[pos].Length == 0)
            {
                ++pos;
                return PeekNext();
            }
            return tokens[pos];
        }
        string line = reader.ReadLine();
        if (line == null)
        {
            // There is no more data to read
            pos = -1;
            return null;
        }
        // Split the line that was read on white space characters
        tokens = line.Split(null);
        pos = 0;
        return PeekNext();

答案 1 :(得分:0)

尽管该方法依赖于外部(类)变量,并且可能应该重构以将其依赖项作为参数,但非递归版本可能如下所示:

private string PeekNext()
{
    while (pos >= 0)
    {
        if (pos < tokens.Length)
        {
            if (tokens[pos].Length == 0)
            {
                ++pos;
                continue;
            }
            return tokens[pos];
        }
        string line = reader.ReadLine();
        if (line == null)
        {
            // There is no more data to read
            pos = -1;
            return null;
        }
        // Split the line that was read on white space characters
        tokens = line.Split(null);
        pos = 0;
    }
    // pos < 0 indicates that there are no more tokens
    return null;
}
相关问题