我基本上有一个字典列表,例如:
List<Dictionary<string, string>>
出于测试目的,我将 36 个字典项提取到列表中,然后在函数结束时返回列表。
奇怪的是,当我填充列表时,我可以看到字典的 Key=>Value 对被添加到 Visual Studio Inspector 的列表中,但是在清除用于填充我的列表的原始字典后,剩下的就是 36列表中的空项目。
是否发生了一些我不知道的奇怪的列表行为?下面包含一个代码片段以供参考...
List<Dictionary<string, string>> allResults = new List<Dictionary<string, string>>();
Dictionary<string, string> selectResult = new Dictionary<string, string>();
MySqlCommand cmd = new MySqlCommand(query, conn);
MySqlDataReader dataReader = cmd.ExecuteReader();
try
{
while (dataReader.Read())
{
for (int i = 0; i < dataReader.FieldCount; i++)
{
selectResult.Add(dataReader.GetName(i).ToString(), dataReader.GetValue(i).ToString());
}
allResults.Add(selectResult);
//Something to do with this next line seems to cause the List to also lose the values stored in the Dictionary, is clearing the dictionary not allowed at this point and the list is simply referencing the Dictionary rather than 'making a copy'?
selectResult.Clear();
}
dataReader.Close();
}
catch { }
this.Close();
return allResults;