1

我是 C# 新手

我遇到了一些问题,我正在通过 Form.cs[Design] 在 Form1 中创建一些图片框

我想从 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();
    }



}

}

4

1 回答 1

1

根据您提供的代码,您的 Form1 或“跑步者”没有被分配。你有两个选择 - 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);
    }     
}

这会将表单传递给灰狗类供您访问,然后在您的表单代码中 -

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();
         }
    }
}

和灰狗班

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);
        }      
    }
}
于 2012-12-14T03:55:24.693 回答