C# 为什么当我清除原始对象时我的列表项被清空?

fle*_*age 4 c# dictionary list

我基本上有一个字典列表,例如:

List<Dictionary<string, string>>
Run Code Online (Sandbox Code Playgroud)

为了测试的目的,我将 36 个字典项目提取到列表中,然后在函数末尾返回该列表。

奇怪的是,当我填充列表时,我可以看到字典的 Key=>Value 对被添加到 Visual Studio 检查器中的列表中,但是在清除用于填充列表的原始字典后,剩下的只有 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;
Run Code Online (Sandbox Code Playgroud)

Ste*_*eve 5

您可以在每个循环的列表中添加相同的字典实例。
只希望当你清除字典时,每个字典都会被清空

要解决该问题,您需要将其添加到您的周期中

   while (dataReader.Read())
   {
        // at every loop, create a new instance of dictionary using the same variable
        Dictionary<string,string> selectResult = new Dictionary<string, string>();
        for (int i = 0; i < dataReader.FieldCount; i++)
        {
            selectResult.Add(dataReader.GetName(i).ToString(), dataReader.GetValue(i).ToString());
        }
        // Adding a different copy of the dictionary in the list
        allResults.Add(selectResult);
    }
Run Code Online (Sandbox Code Playgroud)

不过我还是得问你一下。为什么要用字典来存储列和行?您可以使用 DataTable 获得结果

    DataTable dt = new DataTable();
    dt.Load(dataReader);
Run Code Online (Sandbox Code Playgroud)

忘记列表和词典