IEnumerableGetEnumerator() 执行
因此,我的一个类实现了 IQueryable,它需要 GetEnumerator 方法,代码如下所示:
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;
}
奇怪的部分是,当控件进入第一个方法时,它会跳到它的末尾(进入 GetResults() 之前的右大括号)这是否意味着由于该类实现了 IEnumerable,因此编译器会在不同的线程上隐式执行 GetResults() 方法?
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 of 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,这意味着编译器添加了更多代码,您看不到执行的代码,因为没有表示它的源代码。
当您使用
yield
时,编译器会为您创建枚举器的实现。调用GetResults
并不真正调用您的方法,而是调用该枚举器的构造函数。当您开始从枚举器中读取数据时,您的方法将被第一次调用。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. CallingGetResults
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.