IEnumerable<T> GetEnumerator() exexcution
So one of my classes implements IQueryable for which it need the GetEnumerator method and the code looks like this:
public IEnumerator<T> GetEnumerator()
{
this.ParseExpression(this.expression);
return this.GetResults()
}
private IEnumerator<T> GetResults()
{
//Processes the expression tree.
T t = Activator.CreateInstance(typeof(T));
yield return T;
}
The weird part is when the control enters first method it skips to the end o开发者_如何转开发f it (the closing curly bracket before it enters the GetResults() method. Does this mean that the GetResults() method is executed on a different thread implicitly by the compiler due to the fact that the class implements IEnumerable?
No, it means that there is more code added by the compiler, that you don't see executed as there is no source code representing it.
When you use yield
, the compiler creates the implementation of an enumerator for you. Calling GetResults
doesn't really call your method, instead it calls the constructor of that enumerator. It's when you start reading from the enumerator that your method is being called for the first time.
精彩评论