很抱歉,我知道这个问题以前已经被C#初学者问过一千次(我是其中之一),但我能找到的所有答案都说我需要实例化类,或者让它静态。我的类已实例化,并且我正在尝试访问该实例。任何人都可以查看我的代码并找出出了什么问题吗?
public class RocketSimMain {
public RocketShip test = new RocketShip ();
public static void Main() {
... // Do some setup stuff here
//Run the game loop
while (!EndGameRequested()) {
test.Move(); <- Object instance error here.
}
}
}
如您所见,我正在实例化类并访问实例。唯一有效的方法是在 Main 方法中实例化该类,但是我无法在其他类中访问它。
您必须test
静态才能从静态方法(Main
)使用它。
出现此问题是因为您尝试从静态方法调用非静态类。
要解决它,您必须使它们都成为非静态的:
public RocketShip test = new RocketShip ();
public void Main()
{
... // Do some setup stuff here
//Run the game loop
while (!EndGameRequested())
{
test.Move(); <- Object instance error here.
}
或在方法中本地实例化它:
public static void Main()
{
RocketShip test = new RocketShip ();
... // Do some setup stuff here
//Run the game loop
while (!EndGameRequested())
{
test.Move(); <- Object instance error here.
}
}