Skip to main content
 首页 » 编程设计

c#之使用时间跨度作为字典中的键

2024年02月20日11cyq1162

我有以下代码。它没有向字典中添加新的键值....怎么了??

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); 
} 

作为旁注,仅使用总经过的滴答声或毫秒作为键而不是时间跨度对象可能更有意义