2015-06-09 21 views
-3

我想在C#中構建一個「戰爭」紙牌遊戲。我使用存儲卡的字典手(例如,「心臟的王牌」)作爲鍵和卡值(從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; 
} 

當我打印出上述值,card.Value始終爲0

+6

你有沒有運行在調試器,以確保的'cardPlayed'和'cardValue'值是正確的? –

+2

不可複製。 'player1.Hand [cardPlayed] = cardValue'應該像你期望的那樣完成:將'player1.Hand [cardPlayed]'的字典條目設置爲'cardValue'。設置斷點,遍歷代碼,檢查變量。從顯示的代碼中分析這是不可能的。 – CodeCaster

+1

與你的問題沒有直接關係,但你應該將cardValues移到你的'foreach'循環之外 - 每次迭代你都要重新初始化它。使其成爲類的靜態成員,而不是... –

回答

0

我已經通過調試器運行它,並且ca rdPlayed和cardValue是正確的,但是當我打印出來的值[...] card.Value始終爲0

因爲card.Valueplayer1.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) 
     } 
    } 
} 
+0

謝謝!我對這個失去了主意。 –