我基本上有一个像字典的名单:C#为什么清理原始对象时我的清单项目被清空?
List<Dictionary<string, string>>
对于我取36字典项到列表中,然后在我的函数的端返回的列表中的测试目的。
奇怪的是,当我填充列表时,我可以看到在Visual Studio Inspector中添加到列表中的字典的Key => Value对,但是在清除用于填充我的列表的原始字典时,所有仍然是列表中的36个空项目。
有没有我不知道的一些奇怪的List行为发生?以下代码片段供参考...
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;
真的没有什么好的理由在'while'循环之外定义字典。它只意味着你可能会忘记重新初始化它,或者在循环的范围之前/之后使用它,它只是没有意义被使用。如果你在循环中定义它,你确保它每次都被编译器初始化,并确保它不能用在其它没有意义的上下文中。 – Servy 2013-03-22 16:00:59
是的,我同意并修复答案,但是我仍然对这种数据表的改造感到困惑。 – Steve 2013-03-22 16:03:12
噢,现在我的答案和你的答案是一样的...... – Steve 2013-03-22 16:05:32