【发布时间】:2022-01-08 21:26:06
【问题描述】:
当我启动我的应用程序时,它在“Form1 Test = new Form1();”处给我一个错误在我的课上。这是我的代码。我想使用表单中的标签,因此我使用了“form1 test”。
我创建了一个类,因此我可以在我的 Mainform 中从中调用我的方法,因为我需要使用类对我的应用程序进行编码。当我第一次启动该应用程序时它可以工作,但再次尝试后它就不再工作了。
主要形式:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Tester
{
public partial class Form1 : Form
{
Zombie zombie = new Zombie();
int levens = 3;
public Form1()
{
InitializeComponent();
test1.Text = "Levens: " + "" + levens;
}
private void Form1_Load(object sender, EventArgs e)
{
}
public void Zombie()
{
foreach (Control control in Controls)
{
PictureBox pic = control as PictureBox;
if (pic != null)
{
pic.Top += 1;
if (pic.Top > 600 && pic.Visible == true)
{
pic.Top = 0;
test1.Text = $"Levens: {--levens}";
}
else if (pic.Top > 600 && pic.Visible == false)
{
pic.Visible = true;
pic.Top = 0;
}
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
zombie.MakeZombie(5, this);
}
}
}
类:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Tester
{
class Zombie
{
Random random = new Random();
Form1 Test = new Form1();
private int score = 0;
public void MakeZombie(int aantal, Form formInstance)
{
for (int i = 0; i < aantal; i++)
{
PictureBox picture = new PictureBox();
picture.Image = Properties.Resources.ZombieDik;
picture.Size = new Size(200, 200);
picture.Location = new Point(random.Next(1500), 0);
picture.SizeMode = PictureBoxSizeMode.Zoom;
picture.Click += zombie_Click;
picture.BackColor = Color.Transparent;
formInstance.Controls.Add(picture);
}
}
void zombie_Click(object sender, EventArgs e)
{
PictureBox pic = sender as PictureBox;
pic.Visible = false;
score++;
Test.label2.Text = $"Score: {score}";
Test.Controls.Remove(pic);
pic.Dispose();
}
}
}
【问题讨论】:
-
是的,非常有意义 - 您的应用程序在启动时创建一个
Form1,然后表单创建一个Zombie类的实例,该类又实例化一个新的Form1等等。这种情况会一直发生,直到没有剩余堆栈空间并且您出现堆栈溢出。 -
一个常见错误:要访问主表单,您需要对 it 的引用而不是 新实例。创建一个 Zombie 构造函数 int 传递对 Form1 的引用 ..!只有这样,所有的僵尸才会从主窗体中删除..
-
MakeZombie 方法接收要在其中添加图片框的表单实例。只需将该实例保存在您的内部变量 Test 中,不要创建 Form1 的另一个实例,因为它将启动杀死应用程序的无限循环。
-
另外,不确定在要销毁的控件引发的同一单击事件中删除和销毁控件是否是个好主意。大概是先隐藏它,然后在 Timer 事件中销毁隐藏的 PictureBoxes
-
请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。