IEnumerator<T> 인터페이스
정의
제네릭 컬렉션을 단순하게 반복할 수 있도록 지원합니다.Supports a simple iteration over a generic collection.
generic <typename T>
public interface class IEnumerator : IDisposable, System::Collections::IEnumerator
public interface IEnumerator<out T> : IDisposable, System.Collections.IEnumerator
public interface IEnumerator<T> : IDisposable, System.Collections.IEnumerator
type IEnumerator<'T> = interface
interface IEnumerator
interface IDisposable
type IEnumerator<'T> = interface
interface IDisposable
interface IEnumerator
Public Interface IEnumerator(Of Out T)
Implements IDisposable, IEnumerator
Public Interface IEnumerator(Of T)
Implements IDisposable, IEnumerator
형식 매개 변수
- T
열거할 개체의 형식입니다.The type of objects to enumerate.
이 형식 매개 변수는 공변(Covariant)입니다. 즉, 지정한 형식이나 더 많게 파생된 모든 형식을 사용할 수 있습니다. 공변성(Covariance) 및 반공변성(Contravariance)에 대한 자세한 내용은 제네릭의 공변성(Covariance) 및 반공변성(Contravariance)을 참조하세요.- 파생
- 구현
예제
다음 예제에서는 IEnumerator<T> 사용자 지정 개체의 컬렉션 클래스에 대 한 인터페이스의 구현을 보여 줍니다.The following example shows an implementation of the IEnumerator<T> interface for a collection class of custom objects. 사용자 지정 개체는 형식의 인스턴스이고 Box
컬렉션 클래스는 BoxCollection
입니다.The custom object is an instance of the type Box
, and the collection class is BoxCollection
. 이 코드 예제는에 대해 제공 된 큰 예제의 일부는 ICollection<T> 인터페이스입니다.This code example is part of a larger example provided for the ICollection<T> interface.
// Defines the enumerator for the Boxes collection.
// (Some prefer this class nested in the collection class.)
public class BoxEnumerator : IEnumerator<Box>
{
private BoxCollection _collection;
private int curIndex;
private Box curBox;
public BoxEnumerator(BoxCollection collection)
{
_collection = collection;
curIndex = -1;
curBox = default(Box);
}
public bool MoveNext()
{
//Avoids going beyond the end of the collection.
if (++curIndex >= _collection.Count)
{
return false;
}
else
{
// Set current box to next item in collection.
curBox = _collection[curIndex];
}
return true;
}
public void Reset() { curIndex = -1; }
void IDisposable.Dispose() { }
public Box Current
{
get { return curBox; }
}
object IEnumerator.Current
{
get { return Current; }
}
}
' Defines the enumerator for the Boxes collection.
' (Some prefer this class nested in the collection class.)
Public Class BoxEnumerator
Implements IEnumerator(Of Box)
Private _collection As BoxCollection
Private curIndex As Integer
Private curBox As Box
Public Sub New(ByVal collection As BoxCollection)
MyBase.New()
_collection = collection
curIndex = -1
curBox = Nothing
End Sub
Private Property Box As Box
Public Function MoveNext() As Boolean _
Implements IEnumerator(Of Box).MoveNext
curIndex = curIndex + 1
If curIndex = _collection.Count Then
' Avoids going beyond the end of the collection.
Return False
Else
'Set current box to next item in collection.
curBox = _collection(curIndex)
End If
Return True
End Function
Public Sub Reset() _
Implements IEnumerator(Of Box).Reset
curIndex = -1
End Sub
Public Sub Dispose() _
Implements IEnumerator(Of Box).Dispose
End Sub
Public ReadOnly Property Current() As Box _
Implements IEnumerator(Of Box).Current
Get
If curBox Is Nothing Then
Throw New InvalidOperationException()
End If
Return curBox
End Get
End Property
Private ReadOnly Property Current1() As Object _
Implements IEnumerator.Current
Get
Return Me.Current
End Get
End Property
End Class
' Defines two boxes as equal if they have the same dimensions.
Public Class BoxSameDimensions
Inherits EqualityComparer(Of Box)
Public Overrides Function Equals(ByVal b1 As Box, ByVal b2 As Box) As Boolean
If b1.Height = b2.Height And b1.Length = b2.Length And b1.Width = b2.Width Then
Return True
Else
Return False
End If
End Function
Public Overrides Function GetHashCode(ByVal bx As Box) As Integer
Dim hCode As Integer = bx.Height ^ bx.Length ^ bx.Width
Return hCode.GetHashCode()
End Function
End Class
설명
IEnumerator<T> 는 모든 제네릭 열거자의 기본 인터페이스입니다.IEnumerator<T> is the base interface for all generic enumerators.
합니다 foreach
C# 언어의 (for each
c + +에서는 For Each
Visual Basic에서) 열거자의 복잡성을 숨깁니다.The foreach
statement of the C# language (for each
in C++, For Each
in Visual Basic) hides the complexity of the enumerators. 그러므로 열거자를 직접 조작하는 대신 foreach
를 사용하는 것이 좋습니다.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.
처음에 열거자는 컬렉션의 첫 번째 요소 앞에 배치됩니다.Initially, the enumerator is positioned before the first element in the collection. 이 위치에서 Current는 정의되지 않습니다.At this position, Current is undefined. 따라서 MoveNext의 값을 읽기 전에 Current를 호출하여 열거자를 해당 컬렉션의 첫 번째 요소로 보내야 합니다.Therefore, you must call MoveNext to advance the enumerator to the first element of the collection before reading the value of Current.
Current는 MoveNext가 호출될 때까지 동일한 개체를 반환합니다.Current returns the same object until MoveNext is called. MoveNext는 Current를 다음 요소로 설정합니다.MoveNext sets Current to the next element.
경우 MoveNext 열거자를 컬렉션의 끝 컬렉션의 마지막 요소 뒤에 배치 되는 전달 하 고 MoveNext 반환 false
합니다.If MoveNext passes the end of the collection, the enumerator is positioned after the last element in the collection and MoveNext returns false
. 열거자가 있는 경우이 위치에 대 한 후속 호출은 MoveNext 반환할 수도 false
합니다.When the enumerator is at this position, subsequent calls to MoveNext also return false
. 에 대 한 마지막 호출이 MoveNext false
정의 되어 있지 않으면이 반환 Current 됩니다.If the last call to MoveNext returned false
, Current is undefined. Current를 컬렉션의 첫 번째 요소로 다시 설정할 수 없으므로 대신 새 열거자 인스턴스를 만들어야 합니다.You cannot set Current to the first element of the collection again; you must create a new enumerator instance instead.
Reset메서드는 COM 상호 운용성을 위해 제공 됩니다.The Reset method is provided for COM interoperability. 반드시 구현할 필요는 없습니다. 대신 구현자는만을 throw 할 수 있습니다 NotSupportedException .It does not necessarily need to be implemented; instead, the implementer can simply throw a NotSupportedException. 그러나이 작업을 수행 하도록 선택 하는 경우 기능에 의존 하는 호출자가 없는지 확인 해야 합니다 Reset .However, if you choose to do this, you should make sure no callers are relying on the Reset functionality.
요소 추가, 수정 또는 삭제와 같이 컬렉션이 변경 되 면 열거자의 동작이 정의 되지 않습니다.If changes are made to the collection, such as adding, modifying, or deleting elements, the behavior of the enumerator is undefined.
열거자는 컬렉션에 배타적으로 액세스하지 못하므로 컬렉션을 열거하는 것은 본질적으로 스레드로부터 안전한 프로시저가 아닙니다.The enumerator does not have exclusive access to the collection; therefore, enumerating through a collection is intrinsically not a thread-safe procedure. 열거 동안 스레드 보안을 보장하려면 전체 열거 동안 컬렉션을 잠그면 됩니다.To guarantee thread safety during enumeration, you can lock the collection during the entire enumeration. 여러 스레드에서 컬렉션에 액세스하여 읽고 쓸 수 있도록 허용하려면 사용자 지정 동기화를 구현해야 합니다.To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.
System.Collections.Generic 네임스페이스에서 컬렉션의 기본 구현은 동기화되지 않습니다.Default implementations of collections in the System.Collections.Generic namespace are not synchronized.
구현자 참고
이 인터페이스를 구현 하려면 제네릭이 아닌 인터페이스를 구현 해야 IEnumerator 합니다.Implementing this interface requires implementing the nongeneric IEnumerator interface. MoveNext()및 Reset() 메서드는에 종속 되지 않으며 T
제네릭이 아닌 인터페이스에만 표시 됩니다.The MoveNext() and Reset() methods do not depend on T
, and appear only on the nongeneric interface. Current속성이 두 인터페이스에 모두 표시 되 고 반환 형식이 서로 다릅니다.The Current property appears on both interfaces, and has different return types. 제네릭이 아닌 Current 속성을 명시적 인터페이스 구현으로 구현 합니다.Implement the nongeneric Current property as an explicit interface implementation. 이렇게 하면 제네릭이 아닌 인터페이스의 모든 소비자가 제네릭 인터페이스를 사용할 수 있습니다.This allows any consumer of the nongeneric interface to consume the generic interface.
또한는 메서드를 구현 해야 하 IEnumerator<T> IDisposable 는을 구현 Dispose() 합니다.In addition, IEnumerator<T> implements IDisposable, which requires you to implement the Dispose() method. 이렇게 하면 다른 리소스를 사용 하는 경우 데이터베이스 연결을 닫거나 파일 핸들이 나 유사한 작업을 해제할 수 있습니다.This enables you to close database connections or release file handles or similar operations when using other resources. 추가로 삭제할 리소스가 없는 경우에는 빈 Dispose() 구현을 제공 합니다.If there are no additional resources to dispose of, provide an empty Dispose() implementation.
속성
Current |
컬렉션에서 열거자의 현재 위치에 있는 요소를 가져옵니다.Gets the element in the collection at the current position of the enumerator. |
메서드
Dispose() |
관리되지 않는 리소스의 확보, 해제 또는 다시 설정과 관련된 애플리케이션 정의 작업을 수행합니다.Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. (다음에서 상속됨 IDisposable) |
MoveNext() |
열거자를 컬렉션의 다음 요소로 이동합니다.Advances the enumerator to the next element of the collection. (다음에서 상속됨 IEnumerator) |
Reset() |
컬렉션의 첫 번째 요소 앞의 초기 위치에 열거자를 설정합니다.Sets the enumerator to its initial position, which is before the first element in the collection. (다음에서 상속됨 IEnumerator) |