我正在编写一个二十一点程序,但我的问题是创建具有其他对象列表的对象时的解决方案是什么,但是当我首先创建对象时,列表为空。我认为这就是我收到此错误的原因。下面是我的代码,其中我将玩家初始化为在玩家的构造函数中具有手的实例,但是当我调用方法 playerHand.Hit(card); 时收到“对象引用未设置为对象的实例”错误消息;
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());
}