IEnumerableGetEnumerator() 执行

发布于 2024-10-10 05:12:15 字数 576 浏览 0 评论 0原文

因此,我的一个类实现了 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无力看清 2024-10-17 05:12:15

不,这意味着编译器添加了更多代码,您看不到执行的代码,因为没有表示它的源代码。

当您使用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. 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文