为什么不更新我的字典值?

时间:2015-06-09 12:53:47

标签: c# dictionary

我正在尝试用C#构建一个“战争”纸牌游戏。我使用字典Hand存储卡(例如,“Ace of Hearts”)作为键,并使用卡值(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.

1 个答案:

答案 0 :(得分:0)

  

我已通过调试器运行它,并且cardPlayed和cardValue是正确的,但是当我打印出值[...] card.Value总是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)
        }
    }
}