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 または 'runner' は割り当てられていません。2 つのオプションがあります。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()
        }
}

EDIT:あなたが与えたフォームコードに基づいて -

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 に答える