Access class from another form

前端 未结 3 1814
逝去的感伤
逝去的感伤 2020-12-20 02:48

I\'m struggling to get a class from a different form without making it static, here\'s what I want to do:

//First form
public partial class SetupScreen : For         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-20 03:41

    You could pass a reference of your first form to your second form, or (what I would do), create a public Battleship property on your second form and pass your object that way.

    //First form
    public partial class SetupScreen : Form
    {
        Control myObject;
        public Battleship myBattleship;
    
        public SetupScreen()
        {
            InitializeComponent();
            //Create Class Object
            myBattleship = new Battleship();
    
            Form gameForm = new GameScreen(); // New form object
            gameForm.MyBattleship = myBattleship; // Set property
            gameForm.Show(); // Show form
        }
    }
    
    //Second form 
    public partial class GameScreen : Form
    {
        Control myObject;
        Battleship fredBattleship;
    
        public BattleShip MyBattleship { set; get; }
    
        public GameScreen()
        {
            InitializeComponent();
        }
    }
    

提交回复
热议问题