在安装过程中读取配置文件后,我将 Web 服务保存url
到 a 中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: 指定的强制转换无效。
我最终使用 aFor 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))
我不确定这是否是正确的方法。
是否有任何直接/干净的方式从 a 访问第一个项目Hashtable
?
该Keys
属性是 an ICollection
,而不是 an 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 属性进行测试。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句