我是C#的新手
我遇到了一些问题,我在Form1中通过Form.cs [Design]
创建了一些图片框我想从Form1
访问图片框所以我必须在其他类上创建一个对象来访问Form1.picturebox1
但我可以做对,有人可以帮助我
namespace RaceGame{
class Greyhound
{
Form1 runner;
public int StartingPosition = 13;
public int RacetrackLength = 420;
public PictureBox MyPictureBox = null;
public int Location = 0;
public Random Randomizer;
public void Run()
{
runner.pictureDog1.Location = new Point(13, 100);
}
}
这是Form1
namespace RaceGame{public partial class Form1 : Form
{
Greyhound racing = new Greyhound();
public Form1()
{
InitializeComponent();
}
private void raceButton_Click(object sender, EventArgs e)
{
racing.Run();
}
}
}
答案 0 :(得分:1)
根据您提供的代码,您的Form1或“runner”未被分配。 你有两个选择 - 1)让你的跑步者像这样公开
public Form1 runner;
这将允许您(在您的表单中,而不是您的班级)将表单分配给此属性
public class Form1
{
protected void Form1_Load(object sender, EventArgs e)
{
Greyhound gh = new Greyhound();
gh.runner = this;//this line here
//then you can call gh.Run()
}
}
另一种选择是使用构造函数,如此 -
class Greyhound
{
Form1 runner;
public int StartingPosition = 13;
public int RacetrackLength = 420;
public PictureBox MyPictureBox = null;
public int Location = 0;
public Random Randomizer;
//here
public Greyhound(Form1 form)
{
this.runner = form;
}
public void Run()
{
runner.pictureDog1.Location = new Point(13, 100);
}
}
这会将表单传递给greyhound类供您访问,然后在表单代码中 -
public class Form1
{
protected void Form1_Load(object sender, EventArgs e)
{
Greyhound gh = new Greyhound(this);//pass the form as 'this'
//then you can call gh.Run()
}
}
编辑: 根据您提供的表单代码 -
namespace RaceGame
{
public partial class Form1 : Form
{
Greyhound racing = new Greyhound();
public Form1()
{
InitializeComponent();
}
private void raceButton_Click(object sender, EventArgs e)
{
racing.runner = this;//assign property here
racing.Run();
}
}
}
和Greyhound类
namespace RaceGame
{
class Greyhound
{
public Form1 runner;//make property public
public int StartingPosition = 13;
public int RacetrackLength = 420;
public PictureBox MyPictureBox = null;
public int Location = 0;
public Random Randomizer;
public void Run()
{
runner.pictureDog1.Location = new Point(13, 100);
}
}
}