0

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

1 回答 1

5

你有这一行:

Player dealer = new Dealer();

您没有向我们展示Dealer. 但是,从代码中可以明显看出Dealer : Player. 请注意,您的默认构造函数Player从不初始化Player.playerHand。如果默认构造函数 forDealer调用默认构造函数 for Player(默认情况下确实如此),那么playerHand将是nullfor dealer

所以,我的猜测是playerHand.Hit(card);给你一个NullReferenceExceptionwhen 调用的dealer因为你从来没有初始化Player.playerHand.

要修复它,只需提供一个初始化程序

public Hand playerHand = new Hand();

并从构造函数中删除相应的行Player(string)

最后,顺便说一句,你的类中有太多的public变量。您正在“泄漏”变量,您的班级的消费者可以无限制地修改这些变量并弄乱您的不变量。封装是游戏的名称。

于 2013-06-22T18:32:43.543 回答