CollectionBase.GetEnumerator メソッド

CollectionBase インスタンスを反復処理できる列挙子を返します。

Public Overridable Function GetEnumerator() As IEnumerator _   Implements IEnumerable.GetEnumerator
[C#]
public virtual IEnumerator GetEnumerator();
[C++]
public: virtual IEnumerator* GetEnumerator();
[JScript]
public function GetEnumerator() : IEnumerator;

戻り値

CollectionBase インスタンスの IEnumerator

実装

IEnumerable.GetEnumerator

解説

列挙子は、コレクション内のデータを読み取るためだけに使用できます列挙子を使用して基になるコレクションを変更することはできません。

初期状態では、列挙子はコレクションの最初の要素の前に位置しています。 Reset を実行した場合も、列挙子はこの位置に戻されます。この位置で Current を呼び出すと、例外がスローされます。したがって、 Current の値を読み取る前に、 MoveNext を呼び出して、コレクションの最初の要素に列挙子を進める必要があります。

Current は、 MoveNext または Reset が呼び出されるまでは同じオブジェクトを返します。 MoveNext は、 Current を次の要素に位置付けます。

コレクションの末尾を過ぎると列挙子はコレクションの最後の要素の後に位置付けられ、 MoveNext を呼び出すと false が返されます。 MoveNext への最後の呼び出しで false が返された場合は、 Current を呼び出すと例外がスローされます。 Current をコレクションの最初の要素に再度位置付けるには、 Reset を呼び出し、次に MoveNext を呼び出します。

列挙子は、コレクションが変更されない限り有効です。要素の追加、変更、削除などの変更がコレクションに対して実行されると、列挙子は回復不可能な無効状態になり、次に MoveNext または Reset を呼び出すと、 InvalidOperationException がスローされます。コレクションが MoveNextCurrent の間で変更された場合、列挙子が既に無効になっていても、 Current は設定した要素を返します。

列挙子はコレクションへの排他アクセス権を持たないため、コレクションの列挙処理は、本質的にはスレッド セーフな処理ではありません。コレクションが同期されている場合でも、他のスレッドがそのコレクションを変更する可能性はあり、そのような状況が発生すると列挙子は例外をスローします。列挙処理を確実にスレッド セーフに行うには、列挙中にコレクションをロックするか、他のスレッドによって行われた変更によってスローされる例外をキャッチする方法のいずれかを実行できます。

使用例

[Visual Basic, C#, C++] CollectionBase クラスを実装し、その実装を使用して Int16 オブジェクトのコレクションを作成する方法については、次のコード例を参照してください。

 
Imports System
Imports System.Collections


Public Class Int16Collection
   Inherits CollectionBase


   Default Public Property Item(index As Integer) As Int16
      Get
         Return CType(List(index), Int16)
      End Get
      Set
         List(index) = value
      End Set
   End Property


   Public Function Add(value As Int16) As Integer
      Return List.Add(value)
   End Function 'Add

   Public Function IndexOf(value As Int16) As Integer
      Return List.IndexOf(value)
   End Function 'IndexOf


   Public Sub Insert(index As Integer, value As Int16)
      List.Insert(index, value)
   End Sub 'Insert


   Public Sub Remove(value As Int16)
      List.Remove(value)
   End Sub 'Remove


   Public Function Contains(value As Int16) As Boolean
      ' If value is not of type Int16, this will return false.
      Return List.Contains(value)
   End Function 'Contains


   Protected Overrides Sub OnInsert(index As Integer, value As [Object])
      ' Insert additional code to be run only when inserting values.
   End Sub 'OnInsert


   Protected Overrides Sub OnRemove(index As Integer, value As [Object])
      ' Insert additional code to be run only when removing values.
   End Sub 'OnRemove


   Protected Overrides Sub OnSet(index As Integer, oldValue As [Object], newValue As [Object])
      ' Insert additional code to be run only when setting values.
   End Sub 'OnSet


   Protected Overrides Sub OnValidate(value As [Object])
      If Not value.GetType() Is Type.GetType("System.Int16") Then
         Throw New ArgumentException("value must be of type Int16.", "value")
      End If
   End Sub 'OnValidate 

End Class 'Int16Collection


Public Class SamplesCollectionBase

   Public Shared Sub Main()

      ' Creates and initializes a new CollectionBase.
      Dim myI16 As New Int16Collection()

      ' Adds elements to the collection.
      myI16.Add( 1 )
      myI16.Add( 2 )
      myI16.Add( 3 )
      myI16.Add( 5 )
      myI16.Add( 7 )

      ' Displays the contents of the collection using the enumerator.
      Console.WriteLine("Initial contents of the collection:")
      PrintIndexAndValues(myI16)
      
      ' Searches the collection with Contains and IndexOf.
      Console.WriteLine("Contains 3: {0}", myI16.Contains(3))
      Console.WriteLine("2 is at index {0}.", myI16.IndexOf(2))
      Console.WriteLine()
      
      ' Inserts an element into the collection at index 3.
      myI16.Insert(3, 13)
      Console.WriteLine("Contents of the collection after inserting at index 3:")
      PrintIndexAndValues(myI16)
      
      ' Gets and sets an element using the index.
      myI16(4) = 123
      Console.WriteLine("Contents of the collection after setting the element at index 4 to 123:")
      PrintIndexAndValues(myI16)
      
      ' Removes an element from the collection.
      myI16.Remove(2)

      ' Displays the contents of the collection using the index.
      Console.WriteLine("Contents of the collection after removing the element 2:")
      Dim i As Integer
      For i = 0 To myI16.Count - 1
         Console.WriteLine("   [{0}]:   {1}", i, myI16(i))
      Next i

   End Sub 'Main


   Public Shared Sub PrintIndexAndValues(myCol As Int16Collection)

      Dim i As Integer = 0
      Dim myEnumerator As System.Collections.IEnumerator = myCol.GetEnumerator()
      While myEnumerator.MoveNext()
         Console.WriteLine("   [{0}]:   {1}", i, myEnumerator.Current)
         i += 1
      End While
      Console.WriteLine()

   End Sub 'PrintIndexAndValues

End Class 'SamplesCollectionBase


'This code produces the following output.
'
'Initial contents of the collection:
'   [0]:   1
'   [1]:   2
'   [2]:   3
'   [3]:   5
'   [4]:   7
'
'Contains 3: True
'2 is at index 1.
'
'Contents of the collection after inserting at index 3:
'   [0]:   1
'   [1]:   2
'   [2]:   3
'   [3]:   13
'   [4]:   5
'   [5]:   7
'
'Contents of the collection after setting the element at index 4 to 123:
'   [0]:   1
'   [1]:   2
'   [2]:   3
'   [3]:   13
'   [4]:   123
'   [5]:   7
'
'Contents of the collection after removing the element 2:
'   [0]:   1
'   [1]:   3
'   [2]:   13
'   [3]:   123
'   [4]:   7



[C#] 
using System;
using System.Collections;

public class Int16Collection : CollectionBase  {

   public Int16 this[ int index ]  {
      get  {
         return( (Int16) List[index] );
      }
      set  {
         List[index] = value;
      }
   }

   public int Add( Int16 value )  {
      return( List.Add( value ) );
   }

   public int IndexOf( Int16 value )  {
      return( List.IndexOf( value ) );
   }

   public void Insert( int index, Int16 value )  {
      List.Insert( index, value );
   }

   public void Remove( Int16 value )  {
      List.Remove( value );
   }

   public bool Contains( Int16 value )  {
      // If value is not of type Int16, this will return false.
      return( List.Contains( value ) );
   }

   protected override void OnInsert( int index, Object value )  {
      // Insert additional code to be run only when inserting values.
   }

   protected override void OnRemove( int index, Object value )  {
      // Insert additional code to be run only when removing values.
   }

   protected override void OnSet( int index, Object oldValue, Object newValue )  {
      // Insert additional code to be run only when setting values.
   }

   protected override void OnValidate( Object value )  {
      if ( value.GetType() != Type.GetType("System.Int16") )
         throw new ArgumentException( "value must be of type Int16.", "value" );
   }

}


public class SamplesCollectionBase  {

   public static void Main()  {
 
      // Creates and initializes a new CollectionBase.
      Int16Collection myI16 = new Int16Collection();

      // Adds elements to the collection.
      myI16.Add( (Int16) 1 );
      myI16.Add( (Int16) 2 );
      myI16.Add( (Int16) 3 );
      myI16.Add( (Int16) 5 );
      myI16.Add( (Int16) 7 );

      // Displays the contents of the collection using the enumerator.
      Console.WriteLine( "Initial contents of the collection:" );
      PrintIndexAndValues( myI16 );

      // Searches the collection with Contains and IndexOf.
      Console.WriteLine( "Contains 3: {0}", myI16.Contains( 3 ) );
      Console.WriteLine( "2 is at index {0}.", myI16.IndexOf( 2 ) );
      Console.WriteLine();

      // Inserts an element into the collection at index 3.
      myI16.Insert( 3, (Int16) 13 );
      Console.WriteLine( "Contents of the collection after inserting at index 3:" );
      PrintIndexAndValues( myI16 );

      // Gets and sets an element using the index.
      myI16[4] = 123;
      Console.WriteLine( "Contents of the collection after setting the element at index 4 to 123:" );
      PrintIndexAndValues( myI16 );

      // Removes an element from the collection.
      myI16.Remove( (Int16) 2 );

      // Displays the contents of the collection using the index.
      Console.WriteLine( "Contents of the collection after removing the element 2:" );
      for ( int i = 0; i < myI16.Count; i++ )  {
         Console.WriteLine( "   [{0}]:   {1}", i, myI16[i] );
      }

   }
 
   public static void PrintIndexAndValues( Int16Collection myCol )  {
      int i = 0;
      System.Collections.IEnumerator myEnumerator = myCol.GetEnumerator();
      while ( myEnumerator.MoveNext() )
         Console.WriteLine( "   [{0}]:   {1}", i++, myEnumerator.Current );
      Console.WriteLine();
   }
}


/* 
This code produces the following output.

Initial contents of the collection:
   [0]:   1
   [1]:   2
   [2]:   3
   [3]:   5
   [4]:   7

Contains 3: True
2 is at index 1.

Contents of the collection after inserting at index 3:
   [0]:   1
   [1]:   2
   [2]:   3
   [3]:   13
   [4]:   5
   [5]:   7

Contents of the collection after setting the element at index 4 to 123:
   [0]:   1
   [1]:   2
   [2]:   3
   [3]:   13
   [4]:   123
   [5]:   7

Contents of the collection after removing the element 2:
   [0]:   1
   [1]:   3
   [2]:   13
   [3]:   123
   [4]:   7

*/


[C++] 
#using <mscorlib.dll>
using namespace System;
using namespace System::Collections;

public __gc class Int16Collection : public CollectionBase 
{
public:
   __property Int16 get_Item( int index )
   {
      return *__try_cast<__box Int16*>(List->Item[index]);
   }
   __property void set_Item( int index, Int16 value )
   {
      List->Item[index] = __box(value);
   }

   int Add(Int16 value)
   {
      return(List->Add(__box(value)));
   }

   int IndexOf(Int16 value) 
   {
      return(List->IndexOf(__box(value)));
   }

   void Insert(int index, Int16 value) 
   {
      List->Insert(index, __box(value));
   }

   void Remove(Int16 value)
   {
      List->Remove(__box(value));
   }

   bool Contains(Int16 value)
   {
      // If value is not of type Int16, this will return false.
      return(List->Contains(__box(value)));
   }

protected:
   void OnInsert(int index, Object* value) 
   {
      // Insert additional code to be run only when inserting values.
   }

   void OnRemove(int index, Object* value) 
   {
      // Insert additional code to be run only when removing values.
   }

   void OnSet(int index, Object* oldValue, Object* newValue) 
   {
      // Insert additional code to be run only when setting values.
   }

   void OnValidate(Object* value) 
   {
      if (value->GetType() != Type::GetType(S"System.Int16"))
         throw new ArgumentException(S"value must be of type Int16.", S"value");
   }
};

void PrintIndexAndValues(Int16Collection* myCol)
{
   int i = 0;
   System::Collections::IEnumerator* myEnumerator = myCol->GetEnumerator();
   while (myEnumerator->MoveNext())
      Console::WriteLine(S"   [ {0}]: {1}", __box(i++), myEnumerator->Current);
   Console::WriteLine();
}

int main() 
{

   // Creates and initializes a new CollectionBase.
   Int16Collection* myI16 = new Int16Collection();

   // Adds elements to the collection.
   myI16->Add((Int16) 1);
   myI16->Add((Int16) 2);
   myI16->Add((Int16) 3);
   myI16->Add((Int16) 5);
   myI16->Add((Int16) 7);

   // Displays the contents of the collection using the enumerator.
   Console::WriteLine(S"Initial contents of the collection:");
   PrintIndexAndValues(myI16);

   // Searches the collection with Contains and IndexOf.
   Console::WriteLine(S"Contains 3: {0}", __box(myI16->Contains(3)));
   Console::WriteLine(S"2 is at index {0}.", __box(myI16->IndexOf(2)));
   Console::WriteLine();

   // Inserts an element into the collection at index 3.
   myI16->Insert(3, (Int16) 13);
   Console::WriteLine(S"Contents of the collection after inserting at index 3:");
   PrintIndexAndValues(myI16);

   // Gets and sets an element using the index.
   myI16->Item[4] = 123;
   Console::WriteLine(S"Contents of the collection after setting the element at index 4 to 123:");
   PrintIndexAndValues(myI16);

   // Removes an element from the collection.
   myI16->Remove((Int16) 2);

   // Displays the contents of the collection using the index.
   Console::WriteLine(S"Contents of the collection after removing the element 2:");
   for (int i = 0; i < myI16->Count; i++)
   {
      Console::WriteLine(S"   [ {0}]: {1}", __box(i), __box(myI16->Item[i]));
   }

}

/* 
This code produces the following output.

Initial contents of the collection:
[0]:   1
[1]:   2
[2]:   3
[3]:   5
[4]:   7

Contains 3: True
2 is at index 1.

Contents of the collection after inserting at index 3:
[0]:   1
[1]:   2
[2]:   3
[3]:   13
[4]:   5
[5]:   7

Contents of the collection after setting the element at index 4 to 123:
[0]:   1
[1]:   2
[2]:   3
[3]:   13
[4]:   123
[5]:   7

Contents of the collection after removing the element 2:
[0]:   1
[1]:   3
[2]:   13
[3]:   123
[4]:   7

*/

[JScript] JScript のサンプルはありません。Visual Basic、C#、および C++ のサンプルを表示するには、このページの左上隅にある言語のフィルタ ボタン 言語のフィルタ をクリックします。

必要条件

プラットフォーム: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 ファミリ, .NET Compact Framework - Windows CE .NET

参照

CollectionBase クラス | CollectionBase メンバ | System.Collections 名前空間 | System.Collections.IEnumerator