HashTable的Values为ArrayList应该怎么转换?

ghostwolf_78 2006-07-21 05:13:07
using System;
public class Class1
{
static void Main()
{
System.Collections.Hashtable ht = new ystem.Collections.Hashtable();
System.Collections.ArrayList al2 = new System.Collections.ArrayList();
while(true)
{
string str = Console.ReadLine();

if(str.Equals("exit"))System.Environment.Exit(1);
string [] s = str.Split(' ');
if(ht.ContainsKey(s[0]))
{
System.Collections.ArrayList al = (System.Collections.ArrayList) ht[s[0]] as System.Collections.ArrayList;
al.Add(s[1]);
ht.Remove(s[0]);
ht.Add(s[0],al);
}
else
{
ht.Add(s[0],al2.Add(s[1]));
}
System.Collections.IDictionaryEnumerator ide = ht.GetEnumerator();
while(ide.MoveNext())
{
System.Collections.ArrayList al = (System.Collections.ArrayList)ide.Value as System.Collections.ArrayList;
Console.WriteLine("ht[key]={0}=======================>",ide.Key);
for(int i=0;i<al.Count;i++)
{
Console.WriteLine("ht[key]={0},ht[value]={1}",ide.Key,al[i]);
}

}
}
}
}
说明:hashtable[key=string][value=ArrayList]
我想打印key下的所有Value元素,而Value放的是ArrayList.
所以Value需要转换一下.我用 as 的方式转换报错!

未处理的异常: System.InvalidCastException: 指定的转换无效。
...全文
311 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
ghostwolf_78 2006-07-21
  • 打赏
  • 举报
回复
问题已经解决,3Q
diandian82 2006-07-21
  • 打赏
  • 举报
回复
楼上正确!
brightheroes 2006-07-21
  • 打赏
  • 举报
回复
问题在于这里:

ht.Add(s[0],al2.Add(s[1]));

ArrayList.Add方法,返回的是一个Int

所以你上面的代码,应该分为两行……

al2.Add(s[1]);

ht.Add(s[0],al2);
Eddie005 2006-07-21
  • 打赏
  • 举报
回复
System.Collections.Hashtable ht = new Hashtable();
//.....

object tmp = ht["key1"];//先看看能不能找到值吧
if(tmp!=null)
System.Collections.ArrayList al = tmp as ArrayList;

111,129

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧