C# 无法将现有PictureBox对象分配给对象数组
我正试图解决一本书上的练习题。(没有公布答案) 我需要将表单上的PictureBox对象引用到对象数组。(我真的需要分配四个) 我初始化数组并将变量分配给它。然后,我在数组中的每个项中调用一个方法,但是没有指定PictureBox对象。(空异常) 我有点困惑,因为我在网上公开发现了代码片段,这表明我做得很正确 请输入以下代码以获取指针: 主类C# 无法将现有PictureBox对象分配给对象数组,c#,winforms,C#,Winforms,我正试图解决一本书上的练习题。(没有公布答案) 我需要将表单上的PictureBox对象引用到对象数组。(我真的需要分配四个) 我初始化数组并将变量分配给它。然后,我在数组中的每个项中调用一个方法,但是没有指定PictureBox对象。(空异常) 我有点困惑,因为我在网上公开发现了代码片段,这表明我做得很正确 请输入以下代码以获取指针: 主类 public partial class Form1 : Form { Greyhound[] greyhoundArray = new Grey
public partial class Form1 : Form
{
Greyhound[] greyhoundArray = new Greyhound[4];
public Form1()
{
greyhoundArray[0] = new Greyhound() { Location = 0, MyPictureBox = dog1, RaceTrackLenght = 100, StartingPosition = 0 };
greyhoundArray[1] = new Greyhound() { Location = 0, MyPictureBox = dog2, RaceTrackLenght = 100, StartingPosition = 0 };
greyhoundArray[2] = new Greyhound() { Location = 0, MyPictureBox = dog3, RaceTrackLenght = 100, StartingPosition = 0 };
greyhoundArray[3] = new Greyhound() { Location = 0, MyPictureBox = dog4, RaceTrackLenght = 100, StartingPosition = 0 };
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
foreach (Greyhound greyhound in greyhoundArray)
{
greyhound.Run();
}
}
}
灰狗级
public class Greyhound
{
public int StartingPosition;
public int RaceTrackLenght;
public PictureBox MyPictureBox;
public int Location = 0;
public Random Randomiser;
public void Run()
{
// MessageBox.Show(MyPictureBox.Name + " was called");
Randomiser = new Random();
int distance = Randomiser.Next(0, 4);
Point p = MyPictureBox.Location;
p.X += distance;
MyPictureBox.Location = p;
}
public void TakeStartingPosition()
{ }
}
此外,我可以确认表格上是否存在每个狗图片盒:
Form1.Designer.cs中的代码段
//
// dog1
//
this.dog1.Image = ((System.Drawing.Image)(resources.GetObject("dog1.Image")));
this.dog1.Location = new System.Drawing.Point(17, 21);
this.dog1.Name = "dog1";
this.dog1.Size = new System.Drawing.Size(71, 26);
this.dog1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage;
this.dog1.TabIndex = 2;
this.dog1.TabStop = false;
无法访问窗体构造函数中的窗体控件。您需要在Form\u Load事件处理程序中初始化灰狗的图片框。在初始化灰狗数组之前调用
InitializeComponent()
调用灰狗数组的初始化时,尚未调用InitializeComponent内部的this.dog1=new PictureBox()
,因此将null复制到每个灰狗实例的MyPictureBox
属性中
另外,我认为您的Greyhound类中的Randomiser变量有问题,您应该在声明数组中的任何内容之前初始化窗体的控件,这是因为数组引用了窗体中的项
Greyhound[] greyhoundArray;
public Form1()
{
InitializeComponent();
greyhoundArray = new Greyhound[] {
new Greyhound() {
Location = 0,
MyPictureBox = dog1,
RaceTrackLenght = 100,
StartingPosition = 0
},
new Greyhound() {
Location = 0,
MyPictureBox = dog2,
RaceTrackLenght = 100,
StartingPosition = 0
},
new Greyhound() {
Location = 0,
MyPictureBox = dog3,
RaceTrackLenght = 100,
StartingPosition = 0
},
new Greyhound() {
Location = 0,
MyPictureBox = dog4,
RaceTrackLenght = 100,
StartingPosition = 0
},
}
}
初始化dog1、dog2等值的是InitializeComponent。所以先调用它,然后初始化数组。练习使用调试器,查看greyhoundArray时很容易看到。我猜PictureBoxs在初始化之前是不存在的。谢谢,你试过Run方法吗?每个物体的下一个值是随机的还是相同的?我现在正在研究,所有的“狗”都以相同的速度移动。这确实是一项正在进行的工作。