Access class from another form

前端 未结 3 1829
逝去的感伤
逝去的感伤 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 are getting this error because you are trying to access a non-static field in a static manner.

    Where do you instantiate SetupScreen and GameScreen?

    Why not something like this:

    public partial class SetupScreen : Form
    {
        private Control myObject;
        public Battleship myBattleship;
        private GameScreen gameScreen;
    
        public SetupScreen()
        {
            InitializeComponent();
            //Create Class Object
            myBattleship = new Battleship();
            gameScreen = new GameScreen(this);
        }
    }
    
    public partial class GameScreen : Form
    {
        private Control myObject;
        private Battleship myBattleship;
        private Battleship fredBattleship;
        private SetupScreen setupScreen;
    
        public GameScreen(SetupScreen setupScreen)
        {
            InitializeComponent();
    
            this.setupScreen = setupScreen;
            myBattleship = this.setupScreen.myBattleship;
    
        }
    }
    

    Of course, this will only work if you can instantiate GameScreen in SetupScreen. I could give you a better answer if you tell me where/how you are "launching" these forms.

提交回复
热议问题