【问题标题】:An Object Reference is Required fo Access to Non-Static Member [duplicate]访问非静态成员需要对象引用[重复]
【发布时间】:2016-06-19 17:51:13
【问题描述】:

抱歉,我知道 C# 初学者(我就是其中之一)之前已经问过这个问题一千次,但我能找到的所有答案都说我需要实例化该类或使其成为静态类。我的类 已实例化,我正在尝试访问 instance。谁能看看我的代码并找出问题所在?

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() 访问它。
  • test 本身是一个实例字段,不是静态的。您不能在静态上下文中使用它。

标签: c# class scope static object-reference


【解决方案1】:

您必须将 test 设为静态才能从静态方法 (Main) 中使用它。

【讨论】:

    【解决方案2】:

    出现此问题是因为您尝试从 静态 方法调用 非静态 类。

    要解决它,您必须将它们 都设为非静态:

    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.
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      相关资源
      最近更新 更多