为什么我的代码中出现System.NullReferenceException错误?

时间:2015-10-25 05:25:31

标签: c# winforms nullreferenceexception

我目前正在为我的c#课练习。我在某个特定部分遇到了一些麻烦,非常感谢你的帮助。

我正在进行一项练习,其中我们获得了一个不完整的项目文件。

该项目有多个类,该类用于控制放置在电路板上的方块。

namespace HareAndTortoise {
public partial class SquareControl : PictureBox {

    public const int SQUARE_SIZE = 100;

    private Square square;  // A reference to the corresponding square object

    private BindingList<Player> players;  // References the players in the overall game.

    private bool[] containsPlayers = new bool[6];//HareAndTortoiseGame.MAX_PLAYERS];
    public bool[] ContainsPlayers {
        get {
            return containsPlayers;
        }
        set {
            containsPlayers = value;
        }
    }



    // Font and brush for displaying text inside the square.
    private Font textFont = new Font("Microsoft Sans Serif", 8);
    private Brush textBrush = Brushes.White;

    public SquareControl(Square square, BindingList<Player> players) {

        this.square  = square;
        this.players = players;

        //  Set GUI properties of the whole square.
        Size = new Size(SQUARE_SIZE, SQUARE_SIZE);
        Margin = new Padding(0);  // No spacing around the cell. (Default is 3 pixels.)
        Dock = DockStyle.Fill;
        BorderStyle = BorderStyle.FixedSingle;
        BackColor = Color.CornflowerBlue;

        SetImageWhenNeeded();
    }

    private void SetImageWhenNeeded()
    {

        if (square is Square.Win_Square)
        {
            LoadImageFromFile("Win.png");
            textBrush = Brushes.Black;
        }
        else if (square is Square.Lose_Square)
        {
            LoadImageFromFile("Lose.png");
            textBrush = Brushes.Red;
        }
        else if (square is Square.Chance_Square)
        {
            LoadImageFromFile("monster-green.png");
        }
       else if (square.Name == "Finish")
        {
           LoadImageFromFile("checkered-flag.png");
       }
        else
        {
            // No image needed.
        }

    }

    private void LoadImageFromFile(string fileName) {
        Image image = Image.FromFile(@"Images\" + fileName);
        Image = image;
        SizeMode = PictureBoxSizeMode.StretchImage;  // Zoom is also ok.
    }

    protected override void OnPaint(PaintEventArgs e) {

        //  Due to a limitation in WinForms, don't use base.OnPaint(e) here.

        if (Image != null)
            e.Graphics.DrawImage(Image, e.ClipRectangle);

        string name = square.Name;

        // Create rectangle for drawing.
        float textWidth = textFont.Size * name.Length;
        float textHeight = textFont.Height;
        float textX = e.ClipRectangle.Right - textWidth;
        float textY = e.ClipRectangle.Bottom - textHeight;
        RectangleF drawRect = new RectangleF(textX, textY, textWidth, textHeight);

        // When debugging this method, show the drawing-rectangle on the screen.
        //Pen blackPen = new Pen(Color.Black);
        //e.Graphics.DrawRectangle(blackPen, textX, textY, textWidth, textHeight);

        // Set format of string.
        StringFormat drawFormat = new StringFormat();
        drawFormat.Alignment = StringAlignment.Far;  // Right-aligned.

        // Draw string to screen.
        e.Graphics.DrawString(name, textFont, textBrush, drawRect, drawFormat);

        //  Draw player tokens (when any players are on this square).
        const int PLAYER_TOKENS_PER_ROW = 3;
        const int PLAYER_TOKEN_SIZE = 30;  // pixels.
        const int PLAYER_TOKEN_SPACING = (SQUARE_SIZE - (PLAYER_TOKEN_SIZE * PLAYER_TOKENS_PER_ROW)) / (PLAYER_TOKENS_PER_ROW - 1);

        for (int i = 0; i < containsPlayers.Length; i++) {
            if (containsPlayers[i]) {
                int xPosition = i % PLAYER_TOKENS_PER_ROW;
                int yPosition = i / PLAYER_TOKENS_PER_ROW;
                int xPixels = xPosition * (PLAYER_TOKEN_SIZE + PLAYER_TOKEN_SPACING);
                int yPixels = yPosition * (PLAYER_TOKEN_SIZE + PLAYER_TOKEN_SPACING);
                Brush playerTokenColour = players[i].PlayerTokenColour;
                e.Graphics.FillEllipse(playerTokenColour, xPixels, yPixels, PLAYER_TOKEN_SIZE, PLAYER_TOKEN_SIZE);
            }
        }//endfor
    }

}
}

该计划在以下地点绊倒:

      else if (square.Name == "Finish")
        {
           LoadImageFromFile("checkered-flag.png");
       }

我知道这是因为square.name,但是通过代码,我无法理解为什么square.Name不可识别。

使用此方法从另一个类传递Square

private void SetUpGuiGameBoard() 
    {


        for (int i = 0; i <= 55; i++)
        {

            Square q = Board.GetGameBoardSquare(i);
            SquareControl sq = new SquareControl(q, null);

            int coloumn;
            int row;

            if (i == 0)
            {
                BackColor = Color.BurlyWood;
            }

            if (i == 55)
            {
                BackColor = Color.BurlyWood;
            }

            MapSquareNumToTablePanel(i, out coloumn, out row);

            tableLayoutPanel1.Controls.Add(sq, coloumn, row);

        }

和Squares在这个类中创建

private static Square[] gameBoard = new Square[56];





    static public void SetUpBoard()
        {
    for (int i = 1; i == 55; i++)
        {


    gameBoard[i] = new Square("Ordinary Square", i);       

        }





        gameBoard[0] = new Square("Start", 0);

        gameBoard[4] = new Square.Lose_Square("Lose Square", 4);
        gameBoard[5] = new Square.Chance_Square("Chance Square", 5);

        gameBoard[9] = new Square.Win_Square("Win Square", 9);

        gameBoard[11] = new Square.Chance_Square("Chance Square", 11);

        gameBoard[14] = new Square.Lose_Square("Lose Square", 14);

        gameBoard[17] = new Square.Chance_Square("Chance Square", 17);

        gameBoard[19] = new Square.Win_Square("Win Square", 19);

        gameBoard[24] = new Square.Lose_Square("Lose Square", 24);

        gameBoard[29] = new Square.Win_Square("Win Square", 29);

        gameBoard[34] = new Square.Lose_Square("Lose Square", 34);
        gameBoard[35] = new Square.Chance_Square("Chance Square", 35);

        gameBoard[39] = new Square.Win_Square("Win Square", 39);

        gameBoard[44] = new Square.Lose_Square("Lose Square", 44);

        gameBoard[47] = new Square.Chance_Square("Chance Square", 47);

        gameBoard[49] = new Square.Win_Square("Win Square", 49);

        gameBoard[53] = new Square.Chance_Square("Chance Square", 53);

        gameBoard[55] = new Square("Finish", 56);

    }



        public static Square GetGameBoardSquare(int n)
        {

            return gameBoard[n];

        }

        public static Square StartSquare()
        {
            return gameBoard[0];
        }

        public static Square NextSquare(int n)
        {

            return gameBoard[(n+1)];
        }
    }

1 个答案:

答案 0 :(得分:0)

已经提供的答案是防止任何空引用异常的最佳方法。为了进一步说明,我建议您在调试器到达SquareControl构造函数时检查调用堆栈。此时,您应该检查传入的Square对象为何为“NULL”。这将引导您找到问题的根本原因。希望这会有所帮助。

相关问题