KeyValuePair是通用版本和DictionaryEntry之間的區別是什麼?KeyValuePair VS DictionaryEntry
爲什麼在泛型Dictionary類中使用KeyValuePair而不是DictionaryEntry?
KeyValuePair是通用版本和DictionaryEntry之間的區別是什麼?KeyValuePair VS DictionaryEntry
爲什麼在泛型Dictionary類中使用KeyValuePair而不是DictionaryEntry?
KeyValuePair < T,T>用於遍歷字典< T,T>。這是.Net 2(以及之後)的做事方式。
DictionaryEntry用於遍歷HashTables。這是.Net 1的做事方式。
下面是一個例子:
Dictionary<string, int> MyDictionary = new Dictionary<string, int>();
foreach (KeyValuePair<string, int> item in MyDictionary)
{
// ...
}
Hashtable MyHashtable = new Hashtable();
foreach (DictionaryEntry item in MyHashtable)
{
// ...
}
KeyValuePair<TKey,TValue>
代替DictionaryEntry
被使用,因爲它是泛型。使用KeyValuePair<TKey,TValue>
的好處是我們可以給編譯器提供更多關於我們字典中內容的信息。擴展Chris的例子(我們有兩個包含<string, int>
對的字典)。
Dictionary<string, int> dict = new Dictionary<string, int>();
foreach (KeyValuePair<string, int> item in dict) {
int i = item.Value;
}
Hashtable hashtable = new Hashtable();
foreach (DictionaryEntry item in hashtable) {
// Cast required because compiler doesn't know it's a <string, int> pair.
int i = (int) item.Value;
}
KeyValuePair是泛型,另一個是泛型。建議前者使用前進。 – Gishu 2009-05-25 06:00:48
我認爲他理解一個是泛型,一個是非泛型。我認爲他的問題是我們爲什麼需要兩個? – cdmckay 2009-05-25 19:49:22