我有一个类叫做carroms。当我创建它的对象时,没有错误。但是,当我创建一系列carroms时,会抛出此异常:



我对carroms类的代码:

class carroms
{

    private bool player;

    public bool checkPlayer
    {
        get { return player; }
        set { player = value; }
    }

    private Point center;

    public Point carromCenter
    {
        get { return center; }
        set { center = value; }
    }

    private Point[] points;

    public Point[] carromPoints
    {
        get { return points; }
        set { points = value; }
    }

    private double width;

    public double carromWidth
    {
        get { return width; }
        set { width = value;
        }
    }

    private double height;

    public double carromHeight
    {
        get { return height; }
        set { height = value; }
    }

    public carroms()
    {
        points = new Point[370];
    }

    public Ellipse draw()
    {
        Ellipse myellipse = new Ellipse();
        myellipse.Height = carromHeight;
        myellipse.Width = carromWidth;
        if (checkPlayer == true)
        {
            myellipse.Fill = Brushes.Black;
        }
        else
        {
            myellipse.Fill = Brushes.Beige;
        }
        return myellipse;
    }
}

和我创建对象的代码:
Random randi = new Random();
carroms[] mycarroms = new carroms[5];
mycarroms[0].carromHeight = 100;
mycarroms[0].carromWidth = 100;
mycanvas.Children.Add(mycarroms[0].draw());

最佳答案

您正在创建一个数组,但是是all items added in array are still null
Initialize them first,那么只有您可以访问它。问题在这里-

Random randi = new Random();
carroms[] mycarroms = new carroms[5];
mycarroms[0].carromHeight = 100;  <-- mycarroms[0] will be null

它应该是 -
Random randi = new Random();
carroms[] mycarroms = new carroms[5];
mycarroms[0] = new carroms();
mycarroms[0].carromHeight = 100;

或者您可以使用array initializer对其进行初始化-
Random randi = new Random();
carroms[] mycarroms = new carroms[5]
   {new carroms(), new carroms(), new carroms(), new carroms(), new carroms()};
mycarroms[0].carromHeight = 100;

10-07 18:47