我有以下代码。它没有向字典中添加新的键值....怎么了?
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);
}
我有以下代码。它没有向字典中添加新的键值....怎么了?
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);
}
问题是每次循环执行时您都在实例化一个全新的字典
试试这个:
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);
}
作为旁注,仅使用总经过的滴答声或毫秒作为键而不是时间跨度对象可能更有意义