为什么我的字典值没有更新

本文关键字:更新 我的 字典 为什么 | 更新日期: 2023-09-27 17:54:56

我正在尝试用C#构建一个"战争"纸牌游戏。 我使用字典手,它将卡片(例如,"Ace of Hearts"(存储为键,并将卡片值(从 2 到 14 的整数(作为值。 当我第一次用卡片加载字典时,我没有卡片值,所以只存储 0 作为卡片值。 稍后,我尝试通过对另一个字典执行查找来更新卡值。 我获取卡值并尝试使用正确的卡值更新字典手。 更新不起作用。代码如下所示:

字典:

public class Players
{
    public string Player { get; set; }
    public Dictionary<string, int> Hand { get; set; }
}

法典:

foreach (KeyValuePair<string, int> card in player1.Hand.ToList())
{
    cardPlayed = card.Key;
    // determine rank of card
    string[] cardPhrases = cardPlayed.Split(' ');
    string cardRank = cardPhrases[0];
    // load card values into dictionary
    Dictionary<string, int> cardValues = new Dictionary<string, int>()      
    {
        {"2", 2},
        {"3", 3},
        {"4", 4},
        {"5", 5},
        {"6", 6},
        {"7", 7},
        {"8", 8},
        {"9", 9},
        {"10", 10},
        {"Jack", 11},
        {"Queen", 12},
        {"King", 13},
        {"Ace", 14}
    };
    int cardValue = cardValues[cardRank];
    // add value to dictionary Hand
    // why isn't this working to update card.Value?          
    player1.Hand[cardPlayed] = cardValue;
    result2 = String.Format("{0}-{1}-{2}", player1.Player, card.Key, card.Value);
    resultLabel.Text += result2;
}

当我打印出上面的值时,卡。值始终为 0。

为什么我的字典值没有更新

我已经通过调试器运行了它,并且cardPlay和cardValue是正确的,但是当我打印出值时[...]卡。值始终为 0。

因为card.Value来自 player1.Hand.ToList() ,其中包含设置字典条目之前的字典条目。 KeyValuePair<TKey, TValue>是一个结构体。

您需要打印player1.Hand[cardPlayed].

请参阅以下代码 (http://ideone.com/PW1F4o(:

using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
    public static void Main()
    {
        var dict = new Dictionary<int, string>
        {
            { 0, "Foo"}
        };
        foreach (var kvp in dict.ToList())
        {
            dict[kvp.Key] = "Bar";
            Console.WriteLine(kvp.Value); // Foo (the initial value)
            Console.WriteLine(dict[kvp.Key]); // Bar (the value that was set)
        }
    }
}
相关文章: