當我啟動我的應用程式時,它給我一個錯誤“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();
}
}
}
uj5u.com熱心網友回復:
在zombie_Click()您可以從發件人本身獲得對表單的參考:
void zombie_Click(object sender, EventArgs e)
{
PictureBox pic = sender as PictureBox;
Form1 f1 = pic.FindForm() as Form1;
score ;
f1.label2.Text = $"Score: {score}";
pic.Dispose();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/377596.html
