我正在将后端转换为 c#,我注意到一个奇怪的行为
当我向字典中的列表添加元素时
(实际上在另一本字典中):
很快,它会将值添加到字典中每个元素的每个列表中。
这是代码:
public class Validator_Counter_Model
{
public readonly Dictionary<string,Info_Model> Info;
private Dictionary<string,Dictionary<DateTime,List<int>>> _map = new Dictionary<string, Dictionary<DateTime,List<int>>>();
public Validator_Counter_Model(Dictionary<string, Info_Model> info)
{
Info = info;
}
public void Add(Validation_Element element)
{
/// #### PROBLEM IS HERE!
if (!_map.ContainsKey(element.Id))
{
Dictionary<DateTime, List<int>> newmap = new Dictionary<DateTime, List<int>>();
_map.Add(element.Id, newmap);
}
DateTime fulldate = new Custom_Time_Model(element.Time).RegularTime;
if (!_map[element.Id].ContainsKey(fulldate.Date))
{
List<int> newList = new List<int>();
_map[element.Id].Add(fulldate.Date, newList);
}
_map[element.Id][fulldate.Date].Add(element.Time);
/// #### PROBLEM IS HERE!
}
public void Del(Validation_Element element)
{
DateTime fulldate = new Custom_Time_Model(element.Time).RegularTime;
DateTime date = new DateTime(fulldate.Year, fulldate.Month, fulldate.Day);
_map[element.Id][date].Remove(element.Time);
}
public void Update(Dictionary<string, Dictionary<DateTime, List<int>>> newMap) => _map = newMap;
public Dictionary<string, Dictionary<DateTime, List<int>>> map => _map;
}
}
在这里找到答案
基本上第二个字典(第一个值中的那个)本身不是“字典”,而是另一个字典的引用,这就是为什么向其列表添加值会更改每个键的所有列表的原因
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句