从另一个表单访问类
本文关键字:访问 表单 另一个 | 更新日期: 2023-09-27 18:06:20
我正在努力从不同的形式获得一个类,而不使其静态,这是我想做的:
//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;
}
}
我一直得到错误"非静态字段,方法或属性需要对象引用"
我希望这个类可以被整个表单访问,而不仅仅是一个方法,因此我不想每次都传递它,因为这很麻烦
我不想使类静态,因为它不能被擦除,我该怎么做呢?
您得到这个错误是因为您试图以静态方式访问非静态字段。
你在哪里实例化SetupScreen和gamesscreen ?
为什么不这样呢:
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。如果你告诉我你在哪里/如何"启动"这些表单,我可以给你一个更好的答案。
你可以把你的第一个表单的引用传递给你的第二个表单,或者(我要做的),在你的第二个表单上创建一个公共的Battleship
属性,并以这种方式传递你的对象。
//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();
}
}
必须使用单例模式。所以你的代码必须像这样:
//First form
public partial class SetupScreen : Form
{
public static SetupScreen setupScreenFrm;
Control myObject;
public Battleship myBattleship;
public SetupScreen()
{
setupScreenFrm=this;
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
SetupScreen ssFrm=SetupScreen.setupScreenFrm;
myBattleship = ssFrm.myBattleship;
}
}
,首先,在应用程序的开始,创建一个即时的SetupScreen表单。
现在你可以在任何地方访问SetupScreen