我在寫一個二十一點程序,但我的問題是創建一個具有其他對象列表的對象時的解決方案,但是當我首先創建對象時,列表是空的。我想這就是我得到這個錯誤的原因。下面是我的代碼,我初始化玩家在玩家的構造函數中擁有一個手的實例,但當我調用方法playerHand.Hit(card)時,我得到了「對象引用未設置爲對象實例」的錯誤消息;NullReferenceException未處理
public class Player
{
private string name;
public Hand playerHand;
public Player()
{ }
public Player(string name)
{
this.Name = name;
this.playerHand = new Hand();
}
public string Name
{
get { return name; }
set { name = value; }
}
public void TakeCard(Card card)
{ playerHand.Hit(card); }`
`
public class Hand
{
public List<Card> hand;
public Hand()
{
hand = new List<Card>();
}
public int handValue;`
public void Hit(Card card)
{
hand.Add(card);
}
public int HandValue()
{
foreach (Card card in hand)
handValue += (int)card.value;
return handValue;
}
}
public class Game
{
public Game(IEnumerable<string> playerNames)
{
List<Player> players = new List<Player>();
foreach (string name in playerNames)
players.Add(new Player(name));
Player dealer = new Dealer();
players.Add(dealer);
Deck playingDeck = new Deck();
Deal(playingDeck, players);
Play(playingDeck, players);
DisplayResults(players);
}
public void Deal(Deck deck, List<Player> players)
{
deck.Shuffle();
for (int i = 1; i < 3; i++)
foreach (Player player in players)
player.TakeCard(deck.Deal());
}
調試器說錯誤在哪裏? Play方法在哪裏? –