我想在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
你有沒有運行在調試器,以確保的'cardPlayed'和'cardValue'值是正確的? –
不可複製。 'player1.Hand [cardPlayed] = cardValue'應該像你期望的那樣完成:將'player1.Hand [cardPlayed]'的字典條目設置爲'cardValue'。設置斷點,遍歷代碼,檢查變量。從顯示的代碼中分析這是不可能的。 – CodeCaster
與你的問題沒有直接關係,但你應該將cardValues移到你的'foreach'循環之外 - 每次迭代你都要重新初始化它。使其成爲類的靜態成員,而不是... –