Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
567 views
in Technique[技术] by (71.8m points)

c# - Access class from another form

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 : Form
{
    Control myObject;
    public Battleship myBattleship;

    public SetupScreen()
    {
        InitializeComponent();
        //Create Class Object
        myBattleship = new Battleship();
    }
}

//Launch second form 
public partial class GameScreen : Form
{
    Control myObject;
    Battleship myBattleship;
    Battleship fredBattleship;

    public GameScreen()
    {
        InitializeComponent();
        //Get the class
        myBattleship = SetupScreen.myBattleship;
    }
}

I keep getting the error "an object reference is required for the non-static field, method or property"

I want the class to be accessible by the whole form, not just a single method therefore I don't want to pass it through each time because this is a hassle

I don't want to make the class static since it cannot be erased, how would I go about doing this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...