为什么要向字典添加新值<>覆盖其中的先前值

时间:2018-02-13 16:02:47

标签: c# dictionary

我一直在使用C#中的Dictionary进行此问题。每当我添加一个条目时,字典中的所有条目都填充相同的值。这是代码:

using System;
using System.Collections.Generic;

namespace TESTING
{
    class Program
    {
        /*--------------------Variable Declaration------------------------*/
        public static int NumberOfPlayers = 5;
        public static Dictionary<int, bool> PlayerAI = new Dictionary<int, bool>();
        public static Dictionary<int, Dictionary<string, int>> Players = new Dictionary<int, Dictionary<string, int>>();

        /*----------------------------------------------------------------*/
        public static void Main(string[] args)
        {
            Dictionary<string, int> TMP = new Dictionary<string, int>();
            for (int i = 0; i < NumberOfPlayers; i++)
            {
                Console.WriteLine(i);
                TMP.Clear();
                TMP.Add("Player Target", 0 + (i * 3));
                TMP.Add("Player Cash", 0 + (i * 3));
                TMP.Add("Player Savings", 0 + (i * 3));
                TMP.Add("Borrow Interest", 0 + (i * 3));
                Console.WriteLine(i);
                Players.Add(i, TMP);
                Console.WriteLine(i);
            }

            //----------------------------DEBUG
            for (int i = 0; i < NumberOfPlayers; i++)
            {
                Console.WriteLine(i);
                Dictionary<string, int> PVT = new Dictionary<string, int>();
                PVT = Players[i];
                Console.WriteLine(PVT["Player Target"]);
                Console.WriteLine(PVT["Player Cash"]);
                Console.WriteLine(PVT["Player Savings"]);
                Console.WriteLine(PVT["Borrow Interest"]);

            }
            //------------------------------------

            Console.ReadKey();
        }
    }
}

` 这是输出:

Output

2 个答案:

答案 0 :(得分:7)

您只使用

创建了一个字典
Dictionary<string, int> TMP = new Dictionary<string, int>();

将此词典添加到Players时,会在词典中添加引用。这意味着所有条目都引用相同的字典

要解决此问题,您需要在循环的每次迭代中创建一个新字典:

for (int i = 0; i < NumberOfPlayers; i++)
{
    Console.WriteLine(i);
    Dictionary<string, int> TMP = new Dictionary<string, int>();
    TMP.Add("Player Target", 0 + (i * 3));

答案 1 :(得分:1)

您在$Results += ...中使用了相同的Dictionary。字典只存储引用。您需要创建一个新的Players并存储该引用。