달력

2

« 2025/2 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
2016. 11. 14. 18:24

IEnumerable Interface 프로그래밍/C#2016. 11. 14. 18:24

IEnumerable Interface



Exposes an enumerator, which supports a simple iteration over a non-generic collection.


To browse the .NET Framework source code for this type, see the Reference Source.

Namespace:   System.Collections
Assembly:  mscorlib (in mscorlib.dll)



Remarks

System_CAPS_noteNote

To view the .NET Framework source code for this type, see the Reference Source. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructions.

IEnumerable is the base interface for all non-generic collections that can be enumerated. For the generic version of this interface see System.Collections.Generic.IEnumerable<T>IEnumerable contains a single method, GetEnumerator, which returns an IEnumeratorIEnumeratorprovides the ability to iterate through the collection by exposing a Current property and MoveNext and Reset methods.

It is a best practice to implement IEnumerable and IEnumerator 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 IEnumerator implementation, which is returned by GetEnumerator. When developing with C# you must provide a class that contains a Currentproperty, and MoveNext and Reset methods as described by IEnumerator, but the class does not have to implement IEnumerator.

Examples

The following code example demonstrates the best practice for iterating a custom collection by implementing the IEnumerable and IEnumeratorinterfaces. In this example, members of these interfaces are not explicitly called, but they are implemented to support the use of foreach (For Each in Visual Basic) to iterate through the collection. This example is a complete Console app. To compile the Visual Basic app, change the Startup object to Sub Main in the project’s Properties page.

For a sample that shows how to implement the IEnumerable interface, see Implementing the IEnumerable Interface in a Collection Class

using System;
using System.Collections;

// Simple business object.
public class Person
{
    public Person(string fName, string lName)
    {
        this.firstName = fName;
        this.lastName = lName;
    }

    public string firstName;
    public string lastName;
}

// Collection of Person objects. This class
// implements IEnumerable so that it can be used
// with ForEach syntax.
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];
        }
    }

// Implementation for the GetEnumerator method.
    IEnumerator IEnumerable.GetEnumerator()
    {
       return (IEnumerator) GetEnumerator();
    }

    public PeopleEnum GetEnumerator()
    {
        return new PeopleEnum(_people);
    }
}

// When you implement IEnumerable, you must also implement IEnumerator.
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;
    }

    object IEnumerator.Current
    {
        get
        {
            return Current;
        }
    }

    public Person Current
    {
        get
        {
            try
            {
                return _people[position];
            }
            catch (IndexOutOfRangeException)
            {
                throw new InvalidOperationException();
            }
        }
    }
}

class App
{
    static void Main()
    {
        Person[] peopleArray = new Person[3]
        {
            new Person("John", "Smith"),
            new Person("Jim", "Johnson"),
            new Person("Sue", "Rabon"),
        };

        People peopleList = new People(peopleArray);
        foreach (Person p in peopleList)
            Console.WriteLine(p.firstName + " " + p.lastName);

    }
}

/* This code produces output similar to the following:
 *
 * John Smith
 * Jim Johnson
 * Sue Rabon
 *
 */




IEnumerator Interface


Supports a simple iteration over a non-generic collection.

Namespace:   System.Collections
Assembly:  mscorlib (in mscorlib.dll)

Syntax

[GuidAttribute("496B0ABF-CDEE-11d3-88E8-00902754C43A")]
[ComVisibleAttribute(true)]
public interface IEnumerator

Properties

NameDescription
System_CAPS_pubpropertyCurrent

Gets the current element in the collection.

Methods

NameDescription
System_CAPS_pubmethodMoveNext()

Advances the enumerator to the next element of the collection.

System_CAPS_pubmethodReset()

Sets the enumerator to its initial position, which is before the first element in the collection.

Remarks

IEnumerator is the base interface for all non-generic enumerators.

For the generic version of this interface see IEnumerator<T>.

The foreach statement of the C# language (for each in Visual Basic) hides the complexity of the enumerators. Therefore, using foreach is recommended instead of directly manipulating the enumerator.

Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection.

The Reset method is provided for COM interoperability and does not need to be fully implemented; instead, the implementer can throw a NotSupportedException.

Initially, the enumerator is positioned before the first element in the collection. You must call the MoveNext method to advance the enumerator to the first element of the collection before reading the value of Current; otherwise, Current is undefined.

Current returns the same object until either MoveNext or Reset is called. MoveNext sets Current to the next element.

If MoveNext passes the end of the collection, the enumerator is positioned after the last element in the collection and MoveNext returns false. When the enumerator is at this position, subsequent calls to MoveNext also return false. If the last call to MoveNext returned false, calling Current throws an exception.

To set Current to the first element of the collection again, you can call Reset, if it’s implemented, followed by MoveNext. If Reset is not implemented, you must create a new enumerator instance to return to the first element of the collection.

An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and the next call to MoveNext or Reset throws an InvalidOperationException. If the collection is modified between MoveNext and CurrentCurrent returns the element that it is set to, even if the enumerator is already invalidated.

The enumerator does not have exclusive access to the collection; therefore, enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

The following code example demonstrates the implementation of the IEnumerable and IEnumerator interfaces for a custom collection. In this example, members of these interfaces are not explicitly called, but they are implemented to support the use of foreach (for each in Visual Basic) to iterate through the collection.
















'프로그래밍 > C#' 카테고리의 다른 글

helpful classes  (0) 2016.11.24
Operators  (0) 2016.11.14
Predicate<T> Delegate  (0) 2016.10.18
DateTime, TimeSpan  (0) 2016.10.12
C# 코딩 규칙  (0) 2016.08.28
:
Posted by 지훈2