C# KeyValuePair VS DictionaryEntry

C# KeyValuePair VS DictionaryEntry,c#,C#,作为通用版本的KeyValuePair和DictionaryEntry之间有什么区别 为什么在泛型字典类中使用KeyValuePair而不是DictionaryEntry?KeyValuePair用于迭代字典。这是.NET2(及以后)的工作方式 DictionaryEntry用于迭代哈希表。这是.NET1的工作方式 下面是一个例子: Dictionary<string, int> MyDictionary = new Dictionary<string, int>();

作为通用版本的KeyValuePair和DictionaryEntry之间有什么区别


为什么在泛型字典类中使用KeyValuePair而不是DictionaryEntry?

KeyValuePair用于迭代字典。这是.NET2(及以后)的工作方式

DictionaryEntry用于迭代哈希表。这是.NET1的工作方式

下面是一个例子:

Dictionary<string, int> MyDictionary = new Dictionary<string, int>();
foreach (KeyValuePair<string, int> item in MyDictionary)
{
  // ...
}

Hashtable MyHashtable = new Hashtable();
foreach (DictionaryEntry item in MyHashtable)
{
  // ...
}
Dictionary MyDictionary=newdictionary();
foreach(MyDictionary中的KeyValuePair项)
{
// ...
}
Hashtable MyHashtable=新的Hashtable();
foreach(MyHashtable中的DictionaryEntry项)
{
// ...
}
KeyValuePair
用于代替
字典入口
,因为它是泛型的。使用
KeyValuePair
的优点是,我们可以向编译器提供有关词典中内容的更多信息。扩展Chris的示例(其中我们有两个包含
对的词典)

Dictionary dict=new Dictionary();
foreach(dict中的KeyValuePair项){
int i=项目价值;
}
Hashtable Hashtable=新的Hashtable();
foreach(哈希表中的DictionaryEntry项){
//强制转换是必需的,因为编译器不知道它是一对。
inti=(int)item.Value;
}

KeyValuePair是泛型,另一个是预泛型。建议在fwd中使用前者。我想他知道一个用于泛型,一个用于非泛型。我想他的问题是,为什么我们需要两者?如果他是这么问的,那么,我们并不真的需要两者——只是泛型直到.net 2才可用,他们为了向后兼容而保留了非泛型的东西。有些人可能仍然喜欢使用非泛型的东西,但不推荐使用。这个答案对我来说更有意义。当然是泛型的(limeyied),或者泛型的(yankeyied)。你要找的词是泛型的。;)“泛化”是指更泛化而不是泛化。我认为它应该是泛化的,但我知道什么?我是唯一一个会说一般的人吗?
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;
}