C# 实例化自定义对象

本文关键字:对象 自定义 实例化 | 更新日期: 2023-09-27 18:35:12

嘿,到目前为止,我有,我的for循环中出现空指针错误有人知道为什么吗?谢谢

这是错误消息

对象引用未设置为对象的实例。

    board = new BoardSquare[15][];
    String boardHtml = "";
     for (int i = 0; i < 15; i++) {
            for (int k = 0; k < 15; k++) {
                //if (board[i][k] == null)
                    board[i][k] = new BoardSquare(i, k);
                boardHtml += board[i][k].getHtml();//null pointer error here
            }
        }
     /**
     * A BoardSquare is a square on the FiveInARow Board
     */
    public class BoardSquare {
        private Boolean avail; //is this square open to a piece
        private String color;//the color of the square when taken
        private int x, y; //the position of the square on the board
        /**
         * creates a basic boardSquare
         */
        public BoardSquare(int x, int y) {
            avail = true;
            this.x = x;
            this.y = y;
            color = "red";//now added (thanks)
        }
        /**
         * returns the html form of this square
         */
        public String getHtml(){
            String html = "";
            html = "<div x='" + x + "' y='" + y + "' class='" + (avail ? "available" : color) + "'></div>";
            return html;
        }
        /**
         * if true, sets color to red
         * if false, sets color to green
         */
        public void takeSquare(Boolean red){
            if(red)
                color = "red";
            else 
                color = "green";
        }
    }

C# 实例化自定义对象

字符串字段 颜色 是否实例化? 似乎不像。

有你的空。

 html = "<div x='" + x + "' y='" + y + "' class='" + (avail ? "available" : color) + "'></div>";

构造函数应该是这样的:

public BoardSquare(int x, int y) {
            avail = true;
            this.x = x;
            this.y = y;
            Color = "white";
        }

您正在创建一个数组数组(也称为交错数组),我认为这不是您想要的。 您可能正在寻找一个多维数组:

BoardSquare[,] board = new BoardSquare[15,15];

然后,当您分配给它时:

board[i,k] = new BoardSquare(i, k);
boardHtml += board[i,k].getHtml();