从另一种形式访问类 [英] 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
我不想让类静态,因为它不能被擦除,我将如何去做这个? / p>
I don't want to make the class static since it cannot be erased, how would I go about doing this?
推荐答案
您收到此错误是因为您试图以静态方式访问非静态字段。
You are getting this error because you are trying to access a non-static field in a static manner.
你在哪里实例化SetupScreen和GameScreen?
Where do you instantiate SetupScreen and GameScreen?
为什么不是这样的:
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;
}
}
当然,如果您可以在SetupScreen中实例化GameScreen。我可以给你一个更好的答案,如果你告诉我在哪里/如何启动这些形式。
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.
这篇关于从另一种形式访问类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!