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

Arm*_*ure 0 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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

`这是输出:

产量

Cod*_*ice 7

您只创建了一个字典

Dictionary<string, int> TMP = new Dictionary<string, int>();
Run Code Online (Sandbox Code Playgroud)

当您将此词典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));
Run Code Online (Sandbox Code Playgroud)

等等


归档时间:

查看次数:

348 次

最近记录:

7 年,9 月 前