关于winforms:在运行时向表单添加C#标签

Adding C# labels to a form at Runtime

我正在尝试用C制作一个简单的基于文本的游戏。我希望通过向表单添加标签(而不是使用命令提示)来实现这一点。我无法将它们添加到屏幕上。Visual Studio给出了一个未指定的错误(只是说我有一个未处理的异常):

Object reference not set to an instance of an object

当我试图用一个数组用这些标签填充屏幕时。代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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]);
    }
}

我想知道问题可能藏在哪里?我在google上搜索过,我的代码看起来应该可以工作(除了现在点不随机化尝试填充)。


这一行代码创建一个空数组(即每个元素都不引用任何内容)以存储最多20个标签:

1
Label[] Enemies = new Label[20];

必须显式创建数组中的每个标签:

1
2
3
4
5
6
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编程指南):

1
SomeType[] array4 = new SomeType[10];

The result of this statement depends on whether SomeType is a value
type or a reference type. If it is a value type, the statement creates
an array of 10 elements, each of which has the type SomeType. If
SomeType is a reference type, the statement creates an array of 10
elements, each of which is initialized to a null reference.


创建数组时,所有元素都用该类型的默认值填充。对于所有引用类型,都是null。您需要为数组中的每个项实际创建一个新的Label

1
2
3
4
for (int i = 0; i < Enemies.Length; i++)
{
    Enemies[i] = new Label();
    //...