在安装过程中读取配置文件后,我将Web服务url
保存到Hashtable
中以测试与这些服务的连接性。
在浏览所有保存的值之前,我只想测试第一个值。我使用的密钥是包含服务xml
的整个url
节点,因此我不知道。
首先我对Hashtable
并不了解,所以我尝试使用索引来访问它。假设ht
是填充的Hashtable
,我尝试了此操作:
Dim serviceUrl as String = ht(0).Value
这显然失败了,因为没有key
等于0
,而serviceUrl
只是Nothing
。
然后我尝试使用以下方法访问第一个元素:
Dim firstEntry as DictionaryEntry = ht(ht.Keys(0).ToString())
' Also tried this:
' Dim firstEntry as DictionaryEntry = ht(ht.Keys(0))
在两种情况下我都遇到错误:
System.InvalidCastException:指定的转换无效。
我最终使用For Each
并在第一次迭代后直接退出循环。
For Each entry As DictionaryEntry In ht
Dim serviceUrl as String = entry.Value
'Use it and exit for.
Exit For
Next
好吧,这看起来真的很糟糕。
经过一段时间调试和环顾四周,我使用了一个数组来保存键值:
Dim arr as Object() = new Object(100){}
'Copy the keys to that array.
ht.Keys.CopyTo(arr,0)
'Now I can directly access first item from the Hashtable:
Dim serviceUrl as String = ht(arr(0))
我不确定这是否是正确的方法。
是否可以通过任何直接/干净的方式来访问Hashtable
中的第一项?
答案 0 :(得分:0)
Keys
属性是ICollection
,而不是IList
,因此无法对其进行索引。 ICollection
基本上只是具有IEnumerable
属性的Count
,因此您应该以与IEnumerable
相同的方式对待。这意味着将其枚举以获得第一项。您可以使用LINQ:
Dim firstKey = myHashtable.Keys.Cast(Of Object)().FirstOrDefault()
或者您可以去老学校
Dim firstKey As Object
For Each key In myHashtable.Keys
firstKey = key
Exit For
Next
如果集合可能为空,则可以使用Count属性首先进行测试。