📜  C#|获取一个遍历Hashtable的枚举数

📅  最后修改于: 2021-05-29 17:25:30             🧑  作者: Mango

Hashtable.GetEnumerator方法用于返回迭代Hashtable的IDictionaryEnumerator。

句法:

public virtual System.Collections.IDictionaryEnumerator GetEnumerator ();

返回值:它返回哈希表的IDictionaryEnumerator。

下面的程序说明了Hashtable.GetEnumerator方法的用法:

范例1:

// C# code to get an IDictionaryEnumerator
// that iterates through the Hashtable
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Hashtable named myhash
        Hashtable myhash = new Hashtable();
  
        // Adding key/value pairs in myhash
        myhash.Add("A", "Apple");
        myhash.Add("B", "Banana");
        myhash.Add("C", "Cat");
        myhash.Add("D", "Dog");
        myhash.Add("E", "Elephant");
        myhash.Add("F", "Fish");
  
        // To get an IDictionaryEnumerator
        // for the Hashtable.
        IDictionaryEnumerator myEnumerator = myhash.GetEnumerator();
  
        // If MoveNext passes the end of the
        // collection, the enumerator is positioned
        // after the last element in the collection
        // and MoveNext returns false.
        while (myEnumerator.MoveNext())
            Console.WriteLine(myEnumerator.Key + " --> "
                              + myEnumerator.Value);
    }
}

输出:

B --> Banana
C --> Cat
A --> Apple
F --> Fish
D --> Dog
E --> Elephant

范例2:

// C# code to get an IDictionaryEnumerator
// that iterates through the Hashtable
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Hashtable named myhash
        Hashtable myhash = new Hashtable();
  
        // Adding key/value pairs in myhash
        myhash.Add("I", "first");
        myhash.Add("II", "second");
        myhash.Add("III", "third");
        myhash.Add("IV", "fourth");
        myhash.Add("V", "fifth");
  
        // To get an IDictionaryEnumerator
        // for the Hashtable.
        IDictionaryEnumerator myEnumerator = myhash.GetEnumerator();
  
        // If MoveNext passes the end of the
        // collection, the enumerator is positioned
        // after the last element in the collection
        // and MoveNext returns false.
        while (myEnumerator.MoveNext())
            Console.WriteLine(myEnumerator.Key + " --> "
                              + myEnumerator.Value);
    }
}

输出:

III --> third
IV --> fourth
V --> fifth
II --> second
I --> first

笔记:

  • C#语言的foreach语句隐藏了枚举器的复杂性。因此,建议使用foreach,而不是直接操作枚举器。
  • 枚举数可用于读取集合中的数据,但不能用于修改基础集合。
  • 在调用MoveNext或Reset之前,Current返回相同的对象。 MoveNext将Current设置为下一个元素。
  • 只要集合保持不变,枚举数将保持有效。如果对集合进行了更改(例如添加,修改或删除元素),则枚举数将无法恢复,并且其行为是不确定的。
  • 此方法是O(1)操作。

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.hashtable.getenumerator?view=netframework-4.7.2