读书人

新人关于hashtable的简单的有关问题

发布时间: 2011-12-27 22:22:55 作者: rapoo

新人关于hashtable的简单的问题
using System;
using System.Collections;

class Example
{
public static void Main()
{
// Create a new hash table.
//
Hashtable openWith = new Hashtable();

// Add some elements to the hash table. There are no
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");

// When you use foreach to enumerate hash table elements,
// the elements are retrieved as KeyValuePair objects.
Console.WriteLine();
foreach (DictionaryEntry de in openWith)
{
Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
}
}
}
以上为MSDN范例,里面使用foreach (DictionaryEntry de in openWith)遍历了Hashtable的内容,但怎么看出Hashtable对象是DictionaryEntry类构成的呢,从对象浏览器内只能查到Hashtable支持public virtual System.Collections.IDictionaryEnumerator GetEnumerator(),从IDictionaryEnumerator得到一个DictionaryEntry类对象阿,这怎么来理解呢

[解决办法]
凡是能用 foreach遍历的 都是 实现了 IEnumerable 借口的..
反之则不能用foreach遍历
[解决办法]

探讨
而且为什么直接写
IDictionaryEnumerator myIDE = myHashtable.GetEnumerator();
System.Collections.DictionaryEntry obj = myIDE.Entry;
这样的代码就会提示异常呢

未处理 System.InvalidOperationException
Message="枚举或者尚未开始或者已经结束。"
Source="mscorlib"
StackTrace:
在 System.Collections.Hashtable.HashtableEnumerator.get_Entry()
在 Using_IEnumerator.Main() 位…

[解决办法]
凡是实事了IEnumerable接口的都可以用在foreach中,但不一定都是DirectoryEntry,典型的是MS自己的Dictionary类就是使用的KeyValuePair,foreach中迭代的类型其实是根据IEnumerable的实现类的实例返回的IEnumerator接口的Current属性的具体类型来决定的,这个具体类型在实现IEnumerator接口的时候就定义好了的。
这里的foreach只是一个简化跌代器的操作,但不限于显示声明的迭代器,使用yield关键字声明的同样可以用foreach迭代

读书人网 >C#

热点推荐