博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
How can For each...
阅读量:6413 次
发布时间:2019-06-23

本文共 4260 字,大约阅读时间需要 14 分钟。

Answer:
I understand the IEnumerator/IEnumerable methods and properties and also how they are interrelated. But I fail to understand from the
foreach loop perspective. Say for example, if I say the following line of code, how does the compiler look at
foreach loop and break it down to IEnumerable/IEnumerator for every occurance of
foreach loop in your code. In other words, what happens under the hood? I tried to go through couple of articles on the web. But they were NOT looked from the foreach loop perspective or I might have failed to understand. Could somebody explain with the example or direct me to any articles that explains clearly. All help is greatly appreciated.

 

Answer: To keep it short the compiler doesn't do much. It just translates the foreach code into a while under the hood. Here's an example:

List<int> list = new List<int>;

........

foreach(int item in list)

{

//Do stuff

}

Becomes:

Enumerator<int> enum = ((IEnumerable<int>)list).GetEnumerator();

enum.Reset();

while(enum.MoveNext())

{

int item = enum.Current;

//Do stuff

}

or something very close to that. The acual code compiled most likely has a try / finally block around the while to dispose the enumerator

 

IEnumerable is the base interface for all non-generic collections that can be enumerated. For the generic version of this interface see . IEnumerable contains a single method, , which returns an . provides the ability to iterate through the collection by exposing a property and and methods.

It is a best practice to implement IEnumerable and on your collection classes to enable the foreach (For Each in Visual Basic) syntax, however implementing IEnumerable is not required. If your collection does not implement IEnumerable, you must still follow the iterator pattern to support this syntax by providing a GetEnumerator method that returns an interface, class or struct. When using Visual Basic, you must provide an implementation, which is returned by GetEnumerator. When developing with C# you must provide a class that contains a Current property, and MoveNext and Reset methods as described by , but the class does not have to implement .

 

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Collections;namespace CSharpExam{    public class TestInumerable    {        public static void Run()        {            Person[] peopleArray = new Person[3]        {            new Person("Steven", "Xia"),            new Person("Jim", "Johnson"),            new Person("Sue", "Rabon"),        };            People peopleList = new People(peopleArray);            foreach (Person p in peopleList)                Console.WriteLine(p.firstName + " " + p.lastName);        }    }    public class Person    {        public Person(string fName, string lName)        {            this.firstName = fName;            this.lastName = lName;        }        public string firstName;        public string lastName;    }    public class People //: IEnumerable    {        private Person[] _people;        public People(Person[] pArray)        {            _people = new Person[pArray.Length];            for (int i = 0; i < pArray.Length; i++)            {                _people[i] = pArray[i];            }        }        #region IEnumerable 成员        public PeopleEnum GetEnumerator()        {            return new PeopleEnum(_people);        }        #endregion    }    public class PeopleEnum //: IEnumerator    {        public Person[] _people;        // Enumerators are positioned before the first element         // until the first MoveNext() call.         int position = -1;        public PeopleEnum(Person[] list)        {            _people = list;        }        public bool MoveNext()        {            position++;            return (position < _people.Length);        }        public void Reset()        {            position = -1;        }        public object Current        {            get            {                try                {                    return _people[position];                }                catch (IndexOutOfRangeException)                {                    throw new InvalidOperationException();                }            }        }    }}

 

 

 

转载于:https://www.cnblogs.com/silva/p/3176303.html

你可能感兴趣的文章
Java Web开发详解——XML+DTD+XML Schema+XSLT+Servlet 3.0+JSP 2.2深入剖析与实例应用
查看>>
topcoder srm 680 div1 -3
查看>>
具体数学第二版第四章习题(1)
查看>>
高效前端优化工具--Fiddler入门教程
查看>>
【翻译】我钟爱的HTML5和CSS3在线工具
查看>>
Java多线程学习(吐血超详细总结)
查看>>
css3 变形
查看>>
Win7 64bit 安装Mysql5 出错 无法启动服务。
查看>>
嵌入式 H264参数语法文档: SPS、PPS、IDR以及NALU编码规律
查看>>
初识Opserver,StackExchange的监控解决方案
查看>>
给大家讲解一下JavaScript与后台Java天衣无缝相结合
查看>>
探索HTML5之本地文件系统API - File System API
查看>>
javascript有用代码块(1)
查看>>
libevent 笔记
查看>>
PHP实现人人OAuth登录和API调用
查看>>
redis源码笔记 - initServer
查看>>
FindBugs工具常见问题
查看>>
ECSHOP报错误Deprecated: preg_replace(): The /e modifier is depr
查看>>
【iOS】iOS之Button segue弹出popOver消除(dismiss)问题
查看>>
java多线程系列5-死锁与线程间通信
查看>>