这个 IEnumerable<string>
的具体类型是什么? ?
private IEnumerable<string> GetIEnumerable()
{
yield return "a";
yield return "a";
yield return "a";
}
最佳答案
这是一个编译器生成的类型。编译器生成一个 IEnumerator<string>
返回三个“a”值和一个 IEnumerable<string>
的实现在其 GetEnumerator
中提供其中之一的骨架类方法。
生成的代码看起来像这样*:
// No idea what the naming convention for the generated class is --
// this is really just a shot in the dark.
class GetIEnumerable_Enumerator : IEnumerator<string>
{
int _state;
string _current;
public bool MoveNext()
{
switch (_state++)
{
case 0:
_current = "a";
break;
case 1:
_current = "a";
break;
case 2:
_current = "a";
break;
default:
return false;
}
return true;
}
public string Current
{
get { return _current; }
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
// not sure about this one -- never really tried it...
// I'll just guess
_state = 0;
_current = null;
}
}
class GetIEnumerable_Enumerable : IEnumerable<string>
{
public IEnumerator<string> GetEnumerator()
{
return new GetIEnumerable_Enumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
或者,正如 SLaks 在他的回答中所说,这两个实现最终属于同一个类。我根据之前看过的生成代码的断断续续的内存写了这篇文章;实际上,一个类就足够了,因为上述功能没有理由需要两个。
事实上,仔细想想,这两个实现确实应该属于一个类,因为我只记得使用 yield
的函数。语句的返回类型必须为 either IEnumerable<T>
或 IEnumerator<T>
.
不管怎样,我会让你对我脑补的代码进行更正。
*这纯粹是为了说明目的;我不保证它的真实准确性。它只是根据我在自己的调查中看到的证据,以一般方式展示编译器如何做它所做的事情。
关于c# - 'yield return' 返回什么具体类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3454395/