开发者

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

Does the foreach loop use interfaces IEnumerator and IEnumerable only for iterating the objects of custom types (classes) or also fo开发者_开发技巧r iterating the built-in types (behind the scenes)?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜