返回语法有点奇怪[重复]
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了返回语法有点奇怪[重复]相关的知识,希望对你有一定的参考价值。
这个问题在这里已有答案:
经过几年的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();
}
是否会在其他一些返回发生之前调用自己?
这里发生了什么,从来没有看到一种方法回归自己!?返回什么,空字符串或什么......?或者也许我以前错过了它。
也许简单但令我困惑。
答案
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();
另一答案
尽管该方法依赖于外部(类)变量,并且可能应该重构以将其依赖项作为参数,但非递归版本可能如下所示:
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;
}
以上是关于返回语法有点奇怪[重复]的主要内容,如果未能解决你的问题,请参考以下文章