IEnumerator<T> Rozhraní
Definice
Podporuje jednoduchou iteraci přes obecnou kolekci.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
Parametry typu
- T
Typ objektů k zobrazení výčtu.The type of objects to enumerate.
Tento parametr typu je kovariantní. To znamená, že můžete použít buď zadaný typ, nebo libovolný typ, který je více odvozený. Další informace o kovarianci a kontravarianci najdete v tématu popisujícím kovarianci a kontravarianci u parametrického polymorfismu.- Odvozené
- Implementuje
Příklady
Následující příklad ukazuje implementaci IEnumerator<T> rozhraní pro třídu kolekce vlastních objektů.The following example shows an implementation of the IEnumerator<T> interface for a collection class of custom objects. Vlastní objekt je instancí typu Box a třída kolekce je BoxCollection .The custom object is an instance of the type Box, and the collection class is BoxCollection. Tento příklad kódu je součástí většího příkladu, který je k dispozici pro ICollection<T> rozhraní.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
Poznámky
IEnumerator<T> je základní rozhraní pro všechny obecné enumerátory.IEnumerator<T> is the base interface for all generic enumerators.
foreachPříkaz jazyka C# ( for each v jazyce C++, For Each v Visual Basic) skrývá složitost enumerátorů.The foreach statement of the C# language (for each in C++, For Each in Visual Basic) hides the complexity of the enumerators. Proto foreach se doporučuje použít místo přímé manipulace s enumerátorem.Therefore, using foreach is recommended, instead of directly manipulating the enumerator.
Enumerátory lze používat ke čtení dat v kolekci, nikoli však k úpravě zdrojové kolekce.Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection.
Zpočátku je enumerátor umístěn před první prvek v kolekci.Initially, the enumerator is positioned before the first element in the collection. Na této pozici Current není definován.At this position, Current is undefined. Proto je nutné zavolat MoveNext pro pokračování enumerátoru na první prvek kolekce před čtením hodnoty Current .Therefore, you must call MoveNext to advance the enumerator to the first element of the collection before reading the value of Current.
Current vrátí stejný objekt, dokud MoveNext není volán.Current returns the same object until MoveNext is called. MoveNext nastaví Current na další prvek.MoveNext sets Current to the next element.
Pokud MoveNext předá konec kolekce, enumerátor je umístěn za posledním prvkem v kolekci a MoveNext vrátí false .If MoveNext passes the end of the collection, the enumerator is positioned after the last element in the collection and MoveNext returns false. Když je na této pozici enumerátor, následné volání MoveNext vrátí také false .When the enumerator is at this position, subsequent calls to MoveNext also return false. Pokud poslední volání MoveNext vráceno false Current není definováno.If the last call to MoveNext returned false, Current is undefined. Nemůžete nastavit Current na první prvek kolekce znovu. místo toho je nutné vytvořit novou instanci enumerátoru.You cannot set Current to the first element of the collection again; you must create a new enumerator instance instead.
ResetMetoda je k dispozici pro interoperabilitu modelu COM.The Reset method is provided for COM interoperability. Nutně nemusí být implementováno; místo toho může implementátor jednoduše vyvolat NotSupportedException .It does not necessarily need to be implemented; instead, the implementer can simply throw a NotSupportedException. Pokud se však rozhodnete k tomuto účelu, měli byste se ujistit, že se na funkci nespoléhají žádní volající Reset .However, if you choose to do this, you should make sure no callers are relying on the Reset functionality.
Pokud jsou provedeny změny v kolekci, jako je například přidání, úprava nebo odstranění prvků, chování čítače není definováno.If changes are made to the collection, such as adding, modifying, or deleting elements, the behavior of the enumerator is undefined.
Enumerátor nemá výhradní přístup k této kolekci; Proto výčet prostřednictvím kolekce je vnitřně nebezpečný pro přístup z více vláken.The enumerator does not have exclusive access to the collection; therefore, enumerating through a collection is intrinsically not a thread-safe procedure. Pro zajištění bezpečnosti vlákna během výčtu můžete kolekci uzamknout během celého výčtu.To guarantee thread safety during enumeration, you can lock the collection during the entire enumeration. Chcete-li více vláknům umožnit přístup ke kolekci pro čtení a zápis, musíte implementovat svou vlastní synchronizaci.To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.
Výchozí implementace kolekcí v System.Collections.Generic oboru názvů nejsou synchronizované.Default implementations of collections in the System.Collections.Generic namespace are not synchronized.
Poznámky pro implementátory
Implementace tohoto rozhraní vyžaduje implementaci neobecného IEnumerator rozhraní.Implementing this interface requires implementing the nongeneric IEnumerator interface. MoveNext()Metody a Reset() nejsou závislé na a T jsou zobrazeny pouze v neobecném rozhraní.The MoveNext() and Reset() methods do not depend on T, and appear only on the nongeneric interface. CurrentVlastnost se zobrazí v obou rozhraních a má jiné návratové typy.The Current property appears on both interfaces, and has different return types. Implementujte neobecnou Current vlastnost jako explicitní implementaci rozhraní.Implement the nongeneric Current property as an explicit interface implementation. To umožňuje všem příjemcům neobecného rozhraní využívat obecné rozhraní.This allows any consumer of the nongeneric interface to consume the generic interface.
Kromě toho IEnumerator<T> implementuje implementy IDisposable , které vyžadují implementaci Dispose() metody.In addition, IEnumerator<T> implements IDisposable, which requires you to implement the Dispose() method. Díky tomu můžete zavřít databázová připojení nebo obslužné rutiny souborů verze nebo podobné operace při použití jiných prostředků.This enables you to close database connections or release file handles or similar operations when using other resources. Pokud neexistují žádné další prostředky, které by bylo možné uvolnit, poskytněte prázdnou Dispose() implementaci.If there are no additional resources to dispose of, provide an empty Dispose() implementation.
Vlastnosti
| Current |
Získá prvek v kolekci na aktuální pozici čítače výčtu.Gets the element in the collection at the current position of the enumerator. |
Metody
| Dispose() |
Provede aplikací definované úlohy spojené s uvolněním nebo resetováním nespravovaných prostředků.Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. (Zděděno od IDisposable) |
| MoveNext() |
Posune enumerátor na další prvek kolekce.Advances the enumerator to the next element of the collection. (Zděděno od IEnumerator) |
| Reset() |
Nastaví enumerátor na jeho počáteční pozici, která je před prvním prvkem v kolekci.Sets the enumerator to its initial position, which is before the first element in the collection. (Zděděno od IEnumerator) |