简体   繁体   中英

Does foreach use IEnumerator/IEnumerable for built-in types?

foreach循环是否仅使用接口IEnumeratorIEnumerable来迭代自定义类型(类)的对象,还是迭代内置类型(在幕后)?

Foreach doesn't depend on IEnumerable as such. However, if a type implements it then a foreach loop will be able to enumerate it (pattern-based matching).

Behind the scenes it only needs a GetEnumerator() method and the enumerator must contain Current and MoveNext() .

From MSDN:

  • The collection type:

    • Must be one of the types: interface , class , or struct .
    • Must include an instance method named GetEnumerator that returns a type, for example, Enumerator (explained below).
  • The type Enumerator (a class or struct) must contain:

    • A property named Current that returns ItemType or a type that can be converted to it. The property accessor returns the current element of the collection.
    • A bool method, named MoveNext , that increments the item counter and returns true if there are more items in the collection.

From MSDN - Using foreach with Collections

UPDATED : See updated MSDN page for this - How to: Access a Collection Class with foreach (C# Programming Guide) .

Define enumerator, no IEnumerable declaration.!

public class WorkInfoEnumerator
{
  List<WorkItem > wilist= null;
  int currentIndex = -1;


  public MyClassEnumerator(List<WorkItem > list)
  {
     wilist= list;
  }

  public WorkItem Current
  {
     get
     {
         return wilist[currentIndex];
     }
  }

  public bool MoveNext()
  {
     ++currentIndex;
     if (currentIndex < wilist.Count)
         return true;
     return false;
  }   
}


public class WorkInfo
{
    List<WorkItem > mydata = new List<WorkItem >();
    public WorkInfoEnumerator GetEnumerator()
    {
        return new WorkInfoEnumerator(mydata);
    }
}

Somewhere in code can use :

WorkInfo wi = new WorkInfo();
foreach(WorkItem witem in wi) 
{  
}

foreach uses IEnumerable for both native and custom types. If you look at System.Array for example, which is the base for all array types, it implements IEnumerable.

for-each is language construct and does not really differentiate between custom/built-in types.

for each is not dependent on IEnumerable , it uses pattern based matching. See http://blogs.msdn.com/b/ericlippert/archive/2011/06/30/following-the-pattern.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM