1

I'm trying to make a simple text-based game in C#. How I want to achieve this is by adding labels to a form (instead of using the command prompt). I'm having some trouble adding them to the screen. Visual studio is giving an unspecified error (Only saying I have an unhandled exception):

Object reference not set to an instance of an object

when I try to use an array to populate the screen with these labels. The code:

private void Main_Game_Load(object sender, EventArgs e)
{
    Label[] Enemies = new Label[20];
    Label[] Projectile = new Label[5];
    Font font = new Font(new System.Drawing.FontFamily("Microsoft Sans Serif"), 12);
    Random rand = new Random();
    Point point = new Point(rand.Next(500), rand.Next(500));

    for (int i = 0; i < Enemies.Length; i++)
    {
        Enemies[i].Text = "E";
        Enemies[i].Font = font;
        Enemies[i].BackColor = ColorTranslator.FromHtml("#000000");
        Enemies[i].Location = point;
        Enemies[i].Size = new Size(12, 12);
        Enemies[i].Name = "Enemy"+i.ToString();
        this.Controls.Add(Enemies[i]);
    }
}

I am wondering where the issue might be hiding at? I've googled it and my code seems like it should work (aside from right now point doesn't randomize on attempt to populate).

4

2 に答える 2

3

このコード行は、空の配列 (つまり、各要素が何も参照しない) を作成して、最大 20 個のラベルを格納します。

Label[] Enemies = new Label[20];

配列内の各ラベルを明示的に作成する必要があります。

for (int i = 0; i < Enemies.Length; i++)
{
    //creates a new label and stores a reference to it into i element of the array 
    Enemies[i] = new Label(); 
    //...
}

一次元配列から(C# プログラミング ガイド) :

SomeType[] array4 = new SomeType[10];

このステートメントの結果は、 SomeType が値型か参照型かによって異なります。値型の場合、ステートメントは 10 個の要素の配列を作成します。各要素の型は SomeType です。SomeType が参照型の場合、ステートメントは 10 個の要素の配列を作成し、それぞれが null 参照に初期化されます。

于 2012-12-06T04:20:02.860 に答える
2

配列を作成すると、すべての要素にその型のデフォルト値が入力されます。であるすべての参照型についてnullLabel配列内の各アイテムに対して実際に新しいものを作成する必要があります。

for (int i = 0; i < Enemies.Length; i++)
{
    Enemies[i] = new Label();
    //...
于 2012-12-06T04:19:56.920 に答える