Dictionary
句法:
public System.Collections.Generic.Dictionary
返回值:此方法返回Dictionary
下面的程序说明了Dictionary
范例1:
// C# code to get an IDictionaryEnumerator
// that iterates through the Dictionary
using System;
using System.Collections;
using System.Collections.Generic;
class GFG {
// Driver code
public static void Main()
{
// Creating a Dictionary named myDict
Dictionary myDict =
new Dictionary();
myDict.Add("Australia", "Canberra");
myDict.Add("Belgium", "Brussels");
myDict.Add("Netherlands", "Amsterdam");
myDict.Add("China", "Beijing");
myDict.Add("Russia", "Moscow");
myDict.Add("India", "New Delhi");
// To get an IDictionaryEnumerator
// for the Dictionary
IDictionaryEnumerator myEnumerator =
myDict.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);
}
}
输出:
Australia --> Canberra
Belgium --> Brussels
Netherlands --> Amsterdam
China --> Beijing
Russia --> Moscow
India --> New Delhi
范例2:
// C# code to get an IDictionaryEnumerator
// that iterates through the Dictionary
using System;
using System.Collections;
using System.Collections.Generic;
class GFG {
// Driver code
public static void Main()
{
// Creating a Dictionary named myDict
Dictionary myDict =
new Dictionary();
// Adding key/value pairs in myDict
myDict.Add("I", "C");
myDict.Add("II", "C++");
myDict.Add("III", "Java");
myDict.Add("IV", "Python");
myDict.Add("V", "C#");
// To get an IDictionaryEnumerator
// for the Dictionary
IDictionaryEnumerator myEnumerator =
myDict.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);
}
}
输出:
I --> C
II --> C++
III --> Java
IV --> Python
V --> C#
笔记:
- C#语言的foreach语句隐藏了枚举器的复杂性。因此,建议使用foreach,而不是直接操作枚举器。
- 枚举数可用于读取集合中的数据,但不能用于修改基础集合。
- 在调用MoveNext或Reset之前,Current返回相同的对象。 MoveNext将Current设置为下一个元素。
- 只要集合保持不变,枚举数将保持有效。如果对集合进行了更改(例如添加,修改或删除元素),则枚举数将无法恢复,并且其行为是不确定的。
- 此方法是O(1)操作。
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.dictionary-2.getenumerator?view=netframework-4.7.2