本から演習問題を解こうとしています。(公開された回答なし)
フォームに存在する PictureBox オブジェクトをオブジェクト配列に参照する必要があります。(実際には 4 つを割り当てる必要があります)
配列を初期化し、変数を割り当てます。次に、配列内の各項目内でメソッドを呼び出しますが、PictureBox オブジェクトは割り当てられません。(ヌル例外)
私がこれを正しく行っていることを示すコードのスニペットがネット上で公開されているのを見つけたので、私は少し困惑しています。
ポインター用のコードは次のとおりです。
メインクラス
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()
{ }
}
また、各犬の PictureBox がフォームに存在することも確認できます。
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;