我有一个键值对的散列表(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)));
,也没有工作,关于访问哈希表中的对象有什么想法吗?
首先,您应该使用通用的Dictionary<K, V>
。您的table
变量将变成:
var table = new Dictionary<int, TimeSpan>();
这样就不需要强制转换:
DateTime total = date.Add(table[getInt()]);
在您使用Hashtable
的情况下,您只需要将值转换回来:
DateTime total = date.Add((TimeSpan)table[getInt()]);