我很抱歉,我知道这个问题之前被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方法中实例化类,但后来我无法在其他类中访问它。
答案 0 :(得分:0)
您必须使test
静态才能从静态方法(Main
)中使用它。
答案 1 :(得分:-1)
出现此问题的原因是您尝试从静态方法调用非静态类。
要解决这个问题,你必须让它们都是非静态的:
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.
}
}