Dictionary<TKey,TValue>.IDictionary.GetEnumerator 方法

定义

C#
System.Collections.IDictionaryEnumerator IDictionary.GetEnumerator ();

返回

IDictionaryEnumerator 的一个 IDictionary

实现

示例

下面的代码示例演示如何在 foreach C++) 中使用 Visual Basic for each 中的 语句 (For Each 枚举字典中的键/值对,这将隐藏枚举器的用法。 特别要注意的是,接口的 System.Collections.IDictionary 枚举器返回 DictionaryEntry 对象而不是 KeyValuePair<TKey,TValue> 对象。

代码示例是为 方法提供的更大示例(包括输出)的一 IDictionary.Add 部分。

C#
using System;
using System.Collections;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // Create a new dictionary of strings, with string keys,
        // and access it using the IDictionary interface.
        //
        IDictionary openWith = new Dictionary<string, string>();

        // Add some elements to the dictionary. There are no
        // duplicate keys, but some of the values are duplicates.
        // IDictionary.Add throws an exception if incorrect types
        // are supplied for key or value.
        openWith.Add("txt", "notepad.exe");
        openWith.Add("bmp", "paint.exe");
        openWith.Add("dib", "paint.exe");
        openWith.Add("rtf", "wordpad.exe");
C#
// When you use foreach to enumerate dictionary elements
// with the IDictionary interface, the elements are retrieved
// as DictionaryEntry objects instead of KeyValuePair objects.
Console.WriteLine();
foreach( DictionaryEntry de in openWith )
{
    Console.WriteLine("Key = {0}, Value = {1}",
        de.Key, de.Value);
}
C#
    }
}

注解

出于枚举目的,每个项都是一个 DictionaryEntry 结构。

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

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

最初,枚举数定位在集合中第一个元素的前面。 方法 Reset 还会将枚举器带回此位置。 在此位置上,未定义 Entry。 因此,在读取 的值Entry之前,必须调用 MoveNext 方法以将枚举器推进到集合的第一个元素。

属性 Entry 返回相同的元素, MoveNext 直到调用 或 Reset 方法。 MoveNextEntry 设置为下一个元素。

如果 MoveNext 传递集合的末尾,则枚举器位于集合中的最后一个元素之后,并 MoveNext 返回 false。 当枚举器位于此位置时,对 MoveNext 的后续调用也会返回 false。 如果最后一次MoveNext调用返回,falseEntry则为未定义。 若要再次将 Entry 设置为集合的第一个元素,可以调用 Reset 并接着调用 MoveNext

只要集合保持不变,枚举器就仍有效。 如果对集合进行了更改(例如添加元素或更改容量),枚举器将不可恢复地失效,并且下一次InvalidOperationException调用 MoveNextIEnumerator.Reset 引发 。

仅限 .NET Core 3.0+:唯一不使枚举器 Remove 失效的可变方法是 和 Clear

枚举数没有对集合的独占访问权;因此,从头到尾对一个集合进行枚举在本质上不是一个线程安全的过程。 若要确保枚举过程中的线程安全性,可以在整个枚举过程中锁定集合。 若要允许多个线程访问集合以进行读写操作,则必须实现自己的同步。

System.Collections.Generic 命名空间中集合的默认实现是不同步的。

此方法是 O (1) 操作。

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

另请参阅