【问题标题】:Why aren't my dictionary values being updated?为什么我的字典值没有更新?
【发布时间】:2015-06-09 12:53:47
【问题描述】:

我正在尝试用 C# 构建一个“战争”纸牌游戏。我使用字典 Hand 存储卡片(例如,“红心王牌”)作为键,卡片值(2 到 14 的整数)作为值。当我第一次用卡片加载字典时,我没有卡片值,所以只为卡片值存储 0。后来我尝试通过在另一个字典上执行查找来更新卡值。我获得卡值并尝试用正确的卡值更新字典 Hand 。更新不起作用。代码如下所示:

字典:

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;
}

当我打印出上述值时,card.Value 始终为 0。

【问题讨论】:

  • 您是否在调试器中运行过它以确保cardPlayedcardValue 的值正确?
  • 不可重现。 player1.Hand[cardPlayed] = cardValue 应该完全符合您的预期:将 player1.Hand[cardPlayed] 的字典条目设置为 cardValue。设置断点,单步执行代码,检查变量。从显示的代码中无法分析这一点。
  • 与您的问题没有直接关系,但您应该将 cardValues 移到 foreach 循环之外 - 您每次迭代时都会重新初始化它。将其改为类的静态成员...
  • 我已经通过调试器运行了,cardPlayed和cardValue都是正确的,但是当我打印出来的值如下:result2 = String.Format("
    Player: {0} Card : {1} 卡值: {2}", player1.Player, card.Key, card.Value); ; resultLabel.Text += 结果2; Card.Value 始终为 0。
  • 你能显示 player1.Hand 的代码吗?

标签: c# dictionary


【解决方案1】:

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

因为card.Value 来自player1.Hand.ToList(),其中包含您设置它们之前 的字典条目。 KeyValuePair&lt;TKey, TValue&gt; 是一个结构。

您需要打印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)
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 2011-10-10
    • 2018-03-13
    • 2016-07-18
    相关资源
    最近更新 更多