OrderedDictionary.GetEnumerator 方法

定义

返回循环 IDictionaryEnumerator 访问集合的对象 OrderedDictionary

public:
 virtual System::Collections::IDictionaryEnumerator ^ GetEnumerator();
public virtual System.Collections.IDictionaryEnumerator GetEnumerator();
abstract member GetEnumerator : unit -> System.Collections.IDictionaryEnumerator
override this.GetEnumerator : unit -> System.Collections.IDictionaryEnumerator
Public Overridable Function GetEnumerator () As IDictionaryEnumerator

返回

IDictionaryEnumerator集合的对象OrderedDictionary

实现

示例

下面的代码示例演示如何使用 GetEnumerator 该方法向控制台显示集合的内容 OrderedDictionary 。 在此示例中,该方法 GetEnumerator 用于获取 IDictionaryEnumerator 传递给显示内容的方法的对象。 此代码是可在以下位置 OrderedDictionary查看的较大代码示例的一部分。

// Clear the OrderedDictionary and add new values
myOrderedDictionary.Clear();
myOrderedDictionary.Add("newKey1", "newValue1");
myOrderedDictionary.Add("newKey2", "newValue2");
myOrderedDictionary.Add("newKey3", "newValue3");

// Display the contents of the "new" Dictionary using an enumerator
IDictionaryEnumerator myEnumerator =
    myOrderedDictionary.GetEnumerator();

Console.WriteLine(
    "{0}Displaying the entries of a \"new\" OrderedDictionary.",
    Environment.NewLine);

DisplayEnumerator(myEnumerator);
' Clear the OrderedDictionary and add new values
myOrderedDictionary.Clear()
myOrderedDictionary.Add("newKey1", "newValue1")
myOrderedDictionary.Add("newKey2", "newValue2")
myOrderedDictionary.Add("newKey3", "newValue3")

' Display the contents of the "new" Dictionary Imports an enumerator
Dim myEnumerator As IDictionaryEnumerator = _
    myOrderedDictionary.GetEnumerator()

Console.WriteLine( _
    "{0}Displaying the entries of a 'new' OrderedDictionary.", _
    Environment.NewLine)

DisplayEnumerator(myEnumerator)
// Displays the contents of the OrderedDictionary using its enumerator
public static void DisplayEnumerator(IDictionaryEnumerator myEnumerator)
{
    Console.WriteLine("   KEY                       VALUE");
    while (myEnumerator.MoveNext())
    {
        Console.WriteLine("   {0,-25} {1}",
            myEnumerator.Key, myEnumerator.Value);
    }
}
' Displays the contents of the OrderedDictionary using its enumerator
Public Shared Sub DisplayEnumerator( _
    ByVal myEnumerator As IDictionaryEnumerator)

    Console.WriteLine("   KEY                       VALUE")
    While myEnumerator.MoveNext()
        Console.WriteLine("   {0,-25} {1}", _
            myEnumerator.Key, myEnumerator.Value)
    End While
End Sub

注解

C# 语言的 foreach 语句(for each Visual Basic)隐藏枚举器的复杂性。 因此,建议使用 foreach ,而不是直接操作枚举器。

枚举器可用于读取集合中的数据,但不能用于修改基础集合。

最初,枚举器位于集合中的第一个元素之前。

只要集合保持不变,枚举器就保持有效。 如果对集合进行了更改(例如添加、修改或删除元素),则枚举器不可恢复地失效,并且其行为未定义。

枚举器不具有对集合的独占访问权限;因此,通过集合进行枚举本质上不是线程安全的过程。 若要保证枚举期间的线程安全性,可以在整个枚举期间锁定集合。 若要允许多个线程访问集合进行读取和写入,必须实现自己的同步。

此方法是 O(1) 操作。

适用于