c#哈希表访问对象类型的值

本文关键字:类型 对象 哈希表 访问 | 更新日期: 2023-09-27 18:05:53

我有一个键值对的散列表(Int, new Timespan())和我试图修改的值通过

Hashtable table = new Hashtable();
table.Add(123, new TimeSpan());
...
DateTime date = DateTime.Now;
DateTime total = date.Add(table[getInt()]);

然而,它只会在运行时返回一个TimeSpan对象,不会编译所以我尝试了

 DateTime total = date.Add(Convert.ChangeType(table[getInt()], typeof(TimeSpan)));

,也没有工作,关于访问哈希表中的对象有什么想法吗?

c#哈希表访问对象类型的值

首先,您应该使用通用的Dictionary<K, V>。您的table变量将变成:

var table = new Dictionary<int, TimeSpan>();

这样就不需要强制转换:

DateTime total = date.Add(table[getInt()]);

在您使用Hashtable的情况下,您只需要将值转换回来:

DateTime total = date.Add((TimeSpan)table[getInt()]);