使用Timespan作为字典中的键?

时间:2012-11-20 05:26:35

标签: c# dictionary key-value

我有以下代码。它不是在字典中添加新的键值....什么不对?

while(true)
{
TimeSpan t = // some timespan which is updating every second
int value =  // some value associated with timespan

Dictionary<TimeSpan,int> _dict = new Dictionary<TimeSpan,int>();
_dict.Add(t,value);
}

1 个答案:

答案 0 :(得分:4)

问题是每次循环执行时都要实例化一个全新的字典

试试这个:

Dictionary<TimeSpan,int> _dict = new Dictionary<TimeSpan,int>();
while(true)
{
       TimeSpan t = // some timespan which is updating every second
       int value =  // some value associated with timespan
       _dict.Add(t,value);
}

作为旁注,将经过的总刻度或毫秒用作关键而不是时间跨度对象可能更有意义