返回语法有点奇怪[重复]

问题描述 投票:-2回答:2

这个问题在这里已有答案:

经过几年的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();
}

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

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

也许简单但令我困惑。

c# return
2个回答
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();

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.