IEnumerator<T> 인터페이스
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
제네릭 컬렉션을 단순하게 반복할 수 있도록 지원합니다.
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
열거할 개체의 형식입니다.
이 형식 매개 변수는 공변(Covariant)입니다. 즉, 지정한 형식이나 더 많게 파생된 모든 형식을 사용할 수 있습니다. 공변성(Covariance) 및 반공변성(Contravariance)에 대한 자세한 내용은 제네릭의 공변성(Covariance) 및 반공변성(Contravariance)을 참조하세요.- 파생
- 구현
예제
다음 예제에서는 사용자 지정 개체의 IEnumerator<T> 컬렉션 클래스에 대 한 인터페이스의 구현을 보여 입니다. 사용자 지정 개체는 형식 Box
의 인스턴스이며 컬렉션 클래스는 입니다 BoxCollection
. 이 코드 예제는에 대해 제공 된 큰 예제의 일부는 ICollection<T> 인터페이스입니다.
// 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> 는 모든 제네릭 열거자의 기본 인터페이스입니다.
합니다 foreach
C# 언어의 (for each
c + +에서는 For Each
Visual Basic에서) 열거자의 복잡성을 숨깁니다. 그러므로 열거자를 직접 조작하는 대신 foreach
를 사용하는 것이 좋습니다.
열거자를 사용하여 컬렉션의 데이터를 읽을 수는 있지만 내부 컬렉션을 수정할 수는 없습니다.
처음에 열거자는 컬렉션의 첫 번째 요소 앞에 배치됩니다. 이 위치에서 Current는 정의되지 않습니다. 따라서 MoveNext의 값을 읽기 전에 Current를 호출하여 열거자를 해당 컬렉션의 첫 번째 요소로 보내야 합니다.
Current는 MoveNext가 호출될 때까지 동일한 개체를 반환합니다. MoveNext는 Current를 다음 요소로 설정합니다.
경우 MoveNext 열거자를 컬렉션의 끝 컬렉션의 마지막 요소 뒤에 배치 되는 전달 하 고 MoveNext 반환 false
합니다. 열거자가 있는 경우이 위치에 대 한 후속 호출은 MoveNext 반환할 수도 false
합니다. 반환 false
Current 된 에 대한 MoveNext 마지막 호출이 정의되지 않은 경우
Current를 컬렉션의 첫 번째 요소로 다시 설정할 수 없으므로 대신 새 열거자 인스턴스를 만들어야 합니다.
Reset COM 상호 운용성을 위해 메서드가 제공됩니다. 반드시 구현할 필요는 없습니다. 대신 구현자는 단순히 을 throw할 NotSupportedException수 있습니다. 그러나 이 작업을 수행하도록 선택하는 경우 호출자가 기능에 의존 Reset 하지 않는지 확인해야 합니다.
요소 추가, 수정 또는 삭제와 같이 컬렉션이 변경되면 열거자의 동작이 정의되지 않습니다.
열거자는 컬렉션에 배타적으로 액세스하지 못하므로 컬렉션을 열거하는 것은 본질적으로 스레드로부터 안전한 프로시저가 아닙니다. 열거 동안 스레드 보안을 보장하려면 전체 열거 동안 컬렉션을 잠그면 됩니다. 여러 스레드에서 컬렉션에 액세스하여 읽고 쓸 수 있도록 허용하려면 사용자 지정 동기화를 구현해야 합니다.
System.Collections.Generic 네임스페이스에서 컬렉션의 기본 구현은 동기화되지 않습니다.
구현자 참고
이 인터페이스를 구현하려면 비일반 IEnumerator 인터페이스를 구현해야 합니다. 및 Reset() 메서드는 MoveNext() 에 T
의존하지 않으며 비일반 인터페이스에만 나타납니다. 속성은 Current 두 인터페이스에 모두 표시되며 반환 형식이 다릅니다. 비일반 Current 적 속성을 명시적 인터페이스 구현으로 구현합니다. 이렇게 하면 제네릭이 아닌 인터페이스의 모든 소비자가 제네릭 인터페이스를 사용할 수 있습니다.
또한 은 IEnumerator<T> 메서드를 IDisposable구현해야 하는 를 구현합니다 Dispose() . 이렇게 하면 다른 리소스를 사용할 때 데이터베이스 연결을 닫거나 파일 핸들 또는 유사한 작업을 해제할 수 있습니다. 삭제할 추가 리소스가 없는 경우 빈 Dispose() 구현을 제공합니다.
속성
Current |
컬렉션에서 열거자의 현재 위치에 있는 요소를 가져옵니다. |
메서드
Dispose() |
관리되지 않는 리소스의 확보, 해제 또는 다시 설정과 관련된 애플리케이션 정의 작업을 수행합니다. (다음에서 상속됨 IDisposable) |
MoveNext() |
열거자를 컬렉션의 다음 요소로 이동합니다. (다음에서 상속됨 IEnumerator) |
Reset() |
컬렉션의 첫 번째 요소 앞의 초기 위치에 열거자를 설정합니다. (다음에서 상속됨 IEnumerator) |
적용 대상
추가 정보
.NET
피드백
https://aka.ms/ContentUserFeedback
출시 예정: 2024년 내내 콘텐츠에 대한 피드백 메커니즘으로 GitHub 문제를 단계적으로 폐지하고 이를 새로운 피드백 시스템으로 바꿀 예정입니다. 자세한 내용은 다음을 참조하세요.다음에 대한 사용자 의견 제출 및 보기