อะไรคือความแตกต่างระหว่าง KeyValuePair ซึ่งเป็นเวอร์ชันทั่วไปและ DictionaryEntry?
เหตุใดจึงใช้ KeyValuePair แทน DictionaryEntry ในคลาส Dictionary ทั่วไป
อะไรคือความแตกต่างระหว่าง KeyValuePair ซึ่งเป็นเวอร์ชันทั่วไปและ DictionaryEntry?
เหตุใดจึงใช้ KeyValuePair แทน DictionaryEntry ในคลาส Dictionary ทั่วไป
คำตอบ:
KeyValuePair<TKey,TValue>ถูกใช้แทนDictionaryEntryเนื่องจากมีการระบุชื่อ ข้อดีของการใช้ a KeyValuePair<TKey,TValue>คือเราสามารถให้ข้อมูลเพิ่มเติมเกี่ยวกับสิ่งที่อยู่ในพจนานุกรมของเราแก่คอมไพเลอร์ได้ เพื่อขยายตัวอย่างของคริส (ซึ่งเรามีพจนานุกรมสองเล่มที่มี<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 <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)
{
// ...
}