我正在研究一个简单的 Blackjack纸牌游戏。我正在使用此代码来计算用户分数:
switch (label9.Text)
{
case "J": playerTotal = playerTotal + 10; break;
case "Q": playerTotal = playerTotal + 10; break;
case "K": playerTotal = playerTotal + 10; break;
case "A": playerTotal = playerTotal + 11; break;
default: playerTotal = playerTotal + Convert.ToInt32(label9.Text); break;
}
但我不想一遍又一遍地写这个。所以我将这段代码放在一个函数中:
public void score(Label n, int m)
{
switch (n.Text)
{
case "J": m += 10; break;
case "Q": m += 10; break;
case "K": m += 10; break;
case "A": m += 11; break;
default: m += Convert.ToInt32(n.Text); break;
}
}
现在,问题来了:当我从另一个函数调用 score(label7, playerTotal)
时,playerTotal
的值没有改变.例如:
public void hitPlayer()
{
//ilk hit
if (hitCounter == 0)
{
label7.Text = newDeck.Last();
playerHand[2] = newDeck.Last();
newDeck = newDeck.Take(newDeck.Count() - 1).ToArray();
label7.Visible = true;
pictureBox7.Visible = true;
score(label7, playerTotal); // <<===== 'playerTotal' does not change
aceFound(hitCounter);
label12.Text = playerTotal.ToString();
}
但是,当我使用 switch/case
代码而不将其包装在一个函数中时,playerTotal
的值 确实 改变。我调用 score()
函数的方式有什么问题?
最佳答案
将 m
作为 ref 传递
public void score(Label n, ref int m)
{
switch (n.Text)
{
case "J": m += 10; break;
case "Q": m += 10; break;
case "K": m += 10; break;
case "A": m += 11; break;
default: m += Convert.ToInt32(n.Text); break;
}
}
根据@Andrew 的建议
public void score(Label n, ref int m)
{
switch (n.Text)
{
case "J":
case "Q":
case "K": m += 10; break;
case "A": m += 11; break;
default: m += Convert.ToInt32(n.Text); break;
}
}
score(label7, ref playerTotal);
关于c# - 更改调用函数传递的变量的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27177973/