次の方法で共有


DictionaryBase.GetEnumerator メソッド

DictionaryBase インスタンスを反復処理できる IDictionaryEnumerator を返します。

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

戻り値

DictionaryBase インスタンスの IDictionaryEnumerator

実装

IDictionary.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++] DictionaryBase クラスを実装し、その実装を使用して、 Length が 5 文字以下の String キーと値のディクショナリを作成する方法については、次のコード例を参照してください。

 
Imports System
Imports System.Collections

Public Class ShortStringDictionary
   Inherits DictionaryBase

   Default Public Property Item(key As [String]) As [String]
      Get
         Return CType(Dictionary(key), [String])
      End Get
      Set
         Dictionary(key) = value
      End Set
   End Property

   Public ReadOnly Property Keys() As ICollection
      Get
         Return Dictionary.Keys
      End Get
   End Property

   Public ReadOnly Property Values() As ICollection
      Get
         Return Dictionary.Values
      End Get
   End Property

   Public Sub Add(key As [String], value As [String])
      Dictionary.Add(key, value)
   End Sub 'Add

   Public Function Contains(key As [String]) As Boolean
      Return Dictionary.Contains(key)
   End Function 'Contains

   Public Sub Remove(key As [String])
      Dictionary.Remove(key)
   End Sub 'Remove

   Protected Overrides Sub OnInsert(key As [Object], value As [Object])
      If Not key.GetType() Is Type.GetType("System.String") Then
         Throw New ArgumentException("key must be of type String.", "key")
      Else
         Dim strKey As [String] = CType(key, [String])
         If strKey.Length > 5 Then
            Throw New ArgumentException("key must be no more than 5 characters in length.", "key")
         End If
      End If 
      If Not value.GetType() Is Type.GetType("System.String") Then
         Throw New ArgumentException("value must be of type String.", "value")
      Else
         Dim strValue As [String] = CType(value, [String])
         If strValue.Length > 5 Then
            Throw New ArgumentException("value must be no more than 5 characters in length.", "value")
         End If
      End If
   End Sub 'OnInsert

   Protected Overrides Sub OnRemove(key As [Object], value As [Object])
      If Not key.GetType() Is Type.GetType("System.String") Then
         Throw New ArgumentException("key must be of type String.", "key")
      Else
         Dim strKey As [String] = CType(key, [String])
         If strKey.Length > 5 Then
            Throw New ArgumentException("key must be no more than 5 characters in length.", "key")
         End If
      End If
   End Sub 'OnRemove

   Protected Overrides Sub OnSet(key As [Object], oldValue As [Object], newValue As [Object])
      If Not key.GetType() Is Type.GetType("System.String") Then
         Throw New ArgumentException("key must be of type String.", "key")
      Else
         Dim strKey As [String] = CType(key, [String])
         If strKey.Length > 5 Then
            Throw New ArgumentException("key must be no more than 5 characters in length.", "key")
         End If
      End If 
      If Not newValue.GetType() Is Type.GetType("System.String") Then
         Throw New ArgumentException("newValue must be of type String.", "newValue")
      Else
         Dim strValue As [String] = CType(newValue, [String])
         If strValue.Length > 5 Then
            Throw New ArgumentException("newValue must be no more than 5 characters in length.", "newValue")
         End If
      End If
   End Sub 'OnSet

   Protected Overrides Sub OnValidate(key As [Object], value As [Object])
      If Not key.GetType() Is Type.GetType("System.String") Then
         Throw New ArgumentException("key must be of type String.", "key")
      Else
         Dim strKey As [String] = CType(key, [String])
         If strKey.Length > 5 Then
            Throw New ArgumentException("key must be no more than 5 characters in length.", "key")
         End If
      End If 
      If Not value.GetType() Is Type.GetType("System.String") Then
         Throw New ArgumentException("value must be of type String.", "value")
      Else
         Dim strValue As [String] = CType(value, [String])
         If strValue.Length > 5 Then
            Throw New ArgumentException("value must be no more than 5 characters in length.", "value")
         End If
      End If
   End Sub 'OnValidate 

End Class 'ShortStringDictionary


Public Class SamplesDictionaryBase

   Public Shared Sub Main()

      ' Creates and initializes a new DictionaryBase.
      Dim mySSC As New ShortStringDictionary()

      ' Adds elements to the collection.
      mySSC.Add("One", "a")
      mySSC.Add("Two", "ab")
      mySSC.Add("Three", "abc")
      mySSC.Add("Four", "abcd")
      mySSC.Add("Five", "abcde")

      ' Tries to add a value that is too long.
      Try
         mySSC.Add("Ten", "abcdefghij")
      Catch e As ArgumentException
         Console.WriteLine(e.ToString())
      End Try

      ' Tries to add a key that is too long.
      Try
         mySSC.Add("Eleven", "ijk")
      Catch e As ArgumentException
         Console.WriteLine(e.ToString())
      End Try

      Console.WriteLine()

      ' Displays the contents of the collection using the enumerator.
      Console.WriteLine("Initial contents of the collection:")
      PrintKeysAndValues(mySSC)

      ' Searches the collection with Contains.
      Console.WriteLine("Contains ""Three"": {0}", mySSC.Contains("Three"))
      Console.WriteLine("Contains ""Twelve"": {0}", mySSC.Contains("Twelve"))
      Console.WriteLine()

      ' Removes an element from the collection.
      mySSC.Remove("Two")

      ' Displays the contents of the collection using the Keys property.
      Console.WriteLine("New state of the collection:")
      PrintKeysAndValues3(mySSC)

   End Sub 'Main

   ' Uses the enumerator. 
   Public Shared Sub PrintKeysAndValues(myCol As ShortStringDictionary)
      Dim myDE As DictionaryEntry
      Dim myEnumerator As System.Collections.IEnumerator = myCol.GetEnumerator()
      While myEnumerator.MoveNext()
         If Not (myEnumerator.Current Is Nothing) Then
            myDE = CType(myEnumerator.Current, DictionaryEntry)
            Console.WriteLine("   {0,-5} : {1}", myDE.Key, myDE.Value)
         End If
      End While
      Console.WriteLine()
   End Sub 'PrintKeysAndValues

   ' Uses the foreach statement which hides the complexity of the enumerator.
   Public Shared Sub PrintKeysAndValues2(myCol As ShortStringDictionary)
      Dim myDE As DictionaryEntry
      For Each myDE In  myCol
         Console.WriteLine("   {0,-5} : {1}", myDE.Key, myDE.Value)
      Next myDE
      Console.WriteLine()
   End Sub 'PrintKeysAndValues2

   ' Uses the Keys property and the Item property.
   Public Shared Sub PrintKeysAndValues3(myCol As ShortStringDictionary)
      Dim myKeys As ICollection = myCol.Keys
      Dim k As [String]
      For Each k In  myKeys
         Console.WriteLine("   {0,-5} : {1}", k, myCol(k))
      Next k
      Console.WriteLine()
   End Sub 'PrintKeysAndValues3

End Class 'SamplesDictionaryBase 

 
'This code produces the following output.
'
'System.ArgumentException: value must be no more than 5 characters in length.
'Parameter name: value
'   at ShortStringDictionary.OnValidate(Object key, Object value)
'   at System.Collections.DictionaryBase.System.Collections.IDictionary.Add(Object key, Object value)
'   at SamplesDictionaryBase.Main()
'System.ArgumentException: key must be no more than 5 characters in length.
'Parameter name: key
'   at ShortStringDictionary.OnValidate(Object key, Object value)
'   at System.Collections.DictionaryBase.System.Collections.IDictionary.Add(Object key, Object value)
'   at SamplesDictionaryBase.Main()
'
'Initial contents of the collection:
'   One   : a
'   Four  : abcd
'   Three : abc
'   Two   : ab
'   Five  : abcde
'
'Contains "Three": True
'Contains "Twelve": False
'
'New state of the collection:
'   One   : a
'   Four  : abcd
'   Three : abc
'   Five  : abcde


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

public class ShortStringDictionary : DictionaryBase  {

   public String this[ String key ]  {
      get  {
         return( (String) Dictionary[key] );
      }
      set  {
         Dictionary[key] = value;
      }
   }

   public ICollection Keys  {
      get  {
         return( Dictionary.Keys );
      }
   }

   public ICollection Values  {
      get  {
         return( Dictionary.Values );
      }
   }

   public void Add( String key, String value )  {
      Dictionary.Add( key, value );
   }

   public bool Contains( String key )  {
      return( Dictionary.Contains( key ) );
   }

   public void Remove( String key )  {
      Dictionary.Remove( key );
   }

   protected override void OnInsert( Object key, Object value )  {
      if ( key.GetType() != Type.GetType("System.String") )
         throw new ArgumentException( "key must be of type String.", "key" );
      else  {
         String strKey = (String) key;
         if ( strKey.Length > 5 )
            throw new ArgumentException( "key must be no more than 5 characters in length.", "key" );
      }

      if ( value.GetType() != Type.GetType("System.String") )
         throw new ArgumentException( "value must be of type String.", "value" );
      else  {
         String strValue = (String) value;
         if ( strValue.Length > 5 )
            throw new ArgumentException( "value must be no more than 5 characters in length.", "value" );
      }
   }

   protected override void OnRemove( Object key, Object value )  {
      if ( key.GetType() != Type.GetType("System.String") )
         throw new ArgumentException( "key must be of type String.", "key" );
      else  {
         String strKey = (String) key;
         if ( strKey.Length > 5 )
            throw new ArgumentException( "key must be no more than 5 characters in length.", "key" );
      }
   }

   protected override void OnSet( Object key, Object oldValue, Object newValue )  {
      if ( key.GetType() != Type.GetType("System.String") )
         throw new ArgumentException( "key must be of type String.", "key" );
      else  {
         String strKey = (String) key;
         if ( strKey.Length > 5 )
            throw new ArgumentException( "key must be no more than 5 characters in length.", "key" );
      }

      if ( newValue.GetType() != Type.GetType("System.String") )
         throw new ArgumentException( "newValue must be of type String.", "newValue" );
      else  {
         String strValue = (String) newValue;
         if ( strValue.Length > 5 )
            throw new ArgumentException( "newValue must be no more than 5 characters in length.", "newValue" );
      }
   }

   protected override void OnValidate( Object key, Object value )  {
      if ( key.GetType() != Type.GetType("System.String") )
         throw new ArgumentException( "key must be of type String.", "key" );
      else  {
         String strKey = (String) key;
         if ( strKey.Length > 5 )
            throw new ArgumentException( "key must be no more than 5 characters in length.", "key" );
      }

      if ( value.GetType() != Type.GetType("System.String") )
         throw new ArgumentException( "value must be of type String.", "value" );
      else  {
         String strValue = (String) value;
         if ( strValue.Length > 5 )
            throw new ArgumentException( "value must be no more than 5 characters in length.", "value" );
      }
   }

}


public class SamplesDictionaryBase  {

   public static void Main()  {
 
      // Creates and initializes a new DictionaryBase.
      ShortStringDictionary mySSC = new ShortStringDictionary();

      // Adds elements to the collection.
      mySSC.Add( "One", "a" );
      mySSC.Add( "Two", "ab" );
      mySSC.Add( "Three", "abc" );
      mySSC.Add( "Four", "abcd" );
      mySSC.Add( "Five", "abcde" );

      // Tries to add a value that is too long.
      try  {
         mySSC.Add( "Ten", "abcdefghij" );
      }
      catch ( ArgumentException e )  {
         Console.WriteLine( e.ToString() );
      }

      // Tries to add a key that is too long.
      try  {
         mySSC.Add( "Eleven", "ijk" );
      }
      catch ( ArgumentException e )  {
         Console.WriteLine( e.ToString() );
      }

      Console.WriteLine();

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

      // Searches the collection with Contains.
      Console.WriteLine( "Contains \"Three\": {0}", mySSC.Contains( "Three" ) );
      Console.WriteLine( "Contains \"Twelve\": {0}", mySSC.Contains( "Twelve" ) );
      Console.WriteLine();

      // Removes an element from the collection.
      mySSC.Remove( "Two" );

      // Displays the contents of the collection using the Keys property.
      Console.WriteLine( "New state of the collection:" );
      PrintKeysAndValues3( mySSC );

   }

   // Uses the enumerator. 
   public static void PrintKeysAndValues( ShortStringDictionary myCol )  {
      DictionaryEntry myDE;
      System.Collections.IEnumerator myEnumerator = myCol.GetEnumerator();
      while ( myEnumerator.MoveNext() )
         if ( myEnumerator.Current != null )  {
            myDE = (DictionaryEntry) myEnumerator.Current;
            Console.WriteLine( "   {0,-5} : {1}", myDE.Key, myDE.Value );
         }
      Console.WriteLine();
   }

   // Uses the foreach statement which hides the complexity of the enumerator.
   public static void PrintKeysAndValues2( ShortStringDictionary myCol )  {
      foreach ( DictionaryEntry myDE in myCol )
         Console.WriteLine( "   {0,-5} : {1}", myDE.Key, myDE.Value );
      Console.WriteLine();
   }

   // Uses the Keys property and the Item property.
   public static void PrintKeysAndValues3( ShortStringDictionary myCol )  {
      ICollection myKeys = myCol.Keys;
      foreach ( String k in myKeys )
         Console.WriteLine( "   {0,-5} : {1}", k, myCol[k] );
      Console.WriteLine();
   }

}


/* 
This code produces the following output.

System.ArgumentException: value must be no more than 5 characters in length.
Parameter name: value
   at ShortStringDictionary.OnValidate(Object key, Object value)
   at System.Collections.DictionaryBase.System.Collections.IDictionary.Add(Object key, Object value)
   at SamplesDictionaryBase.Main()
System.ArgumentException: key must be no more than 5 characters in length.
Parameter name: key
   at ShortStringDictionary.OnValidate(Object key, Object value)
   at System.Collections.DictionaryBase.System.Collections.IDictionary.Add(Object key, Object value)
   at SamplesDictionaryBase.Main()

Initial contents of the collection:
   One   : a
   Four  : abcd
   Three : abc
   Two   : ab
   Five  : abcde

Contains "Three": True
Contains "Twelve": False

New state of the collection:
   One   : a
   Four  : abcd
   Three : abc
   Five  : abcde

*/


[C++] 
#using <mscorlib.dll>

using namespace System;
using namespace System::Collections;

public __gc class ShortStringDictionary : public DictionaryBase
{
public:
   __property String* get_Item( String* key )
   {
      return __try_cast<String*>(Dictionary->Item[key]);
   }

   __property void set_Item( String* key, String* value )
   {
      Dictionary->Item[key] = value;
   }

   __property ICollection* get_Keys()
   {
      return(Dictionary->Keys);
   }

   __property ICollection* get_Values()
   {
      return(Dictionary->Values);
   }

   void Add(String* key, String* value) {
      Dictionary->Add(key, value);
   }

   bool Contains(String* key) {
      return(Dictionary->Contains(key));
   }

   void Remove(String* key) {
      Dictionary->Remove(key);
   }

protected:
   void OnInsert(Object* key, Object* value) {
      if (key->GetType() != Type::GetType(S"System.String"))
         throw new ArgumentException(S"key must be of type String.", S"key");
      else {
         String* strKey = __try_cast<String*>(key);
         if (strKey->Length > 5)
            throw new ArgumentException(S"key must be no more than 5 characters in length.", S"key");
      }

      if (value->GetType() != Type::GetType(S"System.String"))
         throw new ArgumentException(S"value must be of type String.", S"value");
      else {
         String* strValue = __try_cast<String*>(value);
         if (strValue->Length > 5)
            throw new ArgumentException(S"value must be no more than 5 characters in length.", S"value");
      }
   }

   void OnRemove(Object* key, Object* value) {
      if (key->GetType() != Type::GetType(S"System.String"))
         throw new ArgumentException(S"key must be of type String.", S"key");
      else {
         String* strKey = __try_cast<String*>(key);
         if (strKey->Length > 5)
            throw new ArgumentException(S"key must be no more than 5 characters in length.", S"key");
      }
   }

   void OnSet(Object* key, Object* oldValue, Object* newValue) {
      if (key->GetType() != Type::GetType(S"System.String"))
         throw new ArgumentException(S"key must be of type String.", S"key");
      else {
         String* strKey = __try_cast<String*>(key);
         if (strKey->Length > 5)
            throw new ArgumentException(S"key must be no more than 5 characters in length.", S"key");
      }

      if (newValue->GetType() != Type::GetType(S"System.String"))
         throw new ArgumentException(S"newValue must be of type String.", S"newValue");
      else {
         String* strValue = __try_cast<String*>(newValue);
         if (strValue->Length > 5)
            throw new ArgumentException(S"newValue must be no more than 5 characters in length.", S"newValue");
      }
   }

   void OnValidate(Object* key, Object* value) {
      if (key->GetType() != Type::GetType(S"System.String"))
         throw new ArgumentException(S"key must be of type String.", S"key");
      else 
      {
         String* strKey = __try_cast<String*>(key);
         if (strKey->Length > 5)
            throw new ArgumentException(S"key must be no more than 5 characters in length.", S"key");
      }

      if (value->GetType() != Type::GetType(S"System.String"))
         throw new ArgumentException(S"value must be of type String.", S"value");
      else 
      {
         String* strValue = __try_cast<String*>(value);
         if (strValue->Length > 5)
            throw new ArgumentException(S"value must be no more than 5 characters in length.", S"value");
      }
   }
};

// Uses the enumerator. 
void PrintKeysAndValues(ShortStringDictionary* myCol)
{
   DictionaryEntry* myDE;
   System::Collections::IEnumerator* myEnumerator = myCol->GetEnumerator();
   while (myEnumerator->MoveNext())
      if (myEnumerator->Current != 0)
      {
         myDE = __try_cast<DictionaryEntry*>(myEnumerator->Current);
         Console::WriteLine(S" {0, -5} : {1}", myDE->Key, myDE->Value);
      }
      Console::WriteLine();
}

// Uses the foreach statement which hides the complexity of the enumerator.
void PrintKeysAndValues2(ShortStringDictionary* myCol) 
{
   IEnumerator* myEnum = myCol->GetEnumerator();
   while (myEnum->MoveNext())
   {
      DictionaryEntry* myDE = __try_cast<DictionaryEntry*>(myEnum->Current);

      Console::WriteLine(S" {0, -5} : {1}", myDE->Key, myDE->Value);
      Console::WriteLine();
   }
}
// Uses the Keys property and the Item property.
void PrintKeysAndValues3(ShortStringDictionary* myCol) 
{
   ICollection* myKeys = myCol->Keys;
   IEnumerator* myEnum = myKeys->GetEnumerator();
   while (myEnum->MoveNext())
   {
      String* k = __try_cast<String*>(myEnum->Current);

      Console::WriteLine(S" {0, -5} : {1}", k, myCol->Item[k]);
      Console::WriteLine();
   }
}

int main() 
{
   // Creates and initializes a new DictionaryBase.
   ShortStringDictionary* mySSC = new ShortStringDictionary();

   // Adds elements to the collection.
   mySSC->Add(S"One", S"a");
   mySSC->Add(S"Two", S"ab");
   mySSC->Add(S"Three", S"abc");
   mySSC->Add(S"Four", S"abcd");
   mySSC->Add(S"Five", S"abcde");

   // Tries to add a value that is too long.
   try
   {
      mySSC->Add(S"Ten", S"abcdefghij");
   }
   catch (ArgumentException* e)
   {
      Console::WriteLine(e);
   }

   // Tries to add a key that is too long.
   try
   {
      mySSC->Add(S"Eleven", S"ijk");
   }
   catch (ArgumentException* e)
   {
      Console::WriteLine(e);
   }

   Console::WriteLine();

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

   // Searches the collection with Contains.
   Console::WriteLine(S"Contains \"Three\": {0}", __box(mySSC->Contains(S"Three")));
   Console::WriteLine(S"Contains \"Twelve\": {0}", __box(mySSC->Contains(S"Twelve")));
   Console::WriteLine();

   // Removes an element from the collection.
   mySSC->Remove(S"Two");

   // Displays the contents of the collection using the Keys property.
   Console::WriteLine(S"New state of the collection:");
   PrintKeysAndValues3(mySSC);
}

/* 
This code produces the following output.

System::ArgumentException: value must be no more than 5 characters in length.
Parameter name: value
at ShortStringDictionary::OnValidate(Object key, Object value)
at System::Collections::DictionaryBase::System.Collections::IDictionary*.Add(Object key, Object value)
at SamplesDictionaryBase::Main()
System::ArgumentException: key must be no more than 5 characters in length.
Parameter name: key
at ShortStringDictionary::OnValidate(Object key, Object value)
at System::Collections::DictionaryBase::System.Collections::IDictionary*.Add(Object key, Object value)
at SamplesDictionaryBase::Main()

Initial contents of the collection:
One   : a
Four  : abcd
Three : abc
Two   : ab
Five  : abcde

Contains S"Three": True
Contains S"Twelve": False

New state of the collection:
One   : a
Four  : abcd
Three : abc
Five  : abcde

*/

[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 ファミリ

参照

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