Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 访问非静态成员需要对象引用_C#_Class_Scope_Static_Object Reference - Fatal编程技术网

C# 访问非静态成员需要对象引用

C# 访问非静态成员需要对象引用,c#,class,scope,static,object-reference,C#,Class,Scope,Static,Object Reference,我很抱歉,我知道C#初学者(我就是其中之一)曾经问过上千次这个问题,但是我能找到的所有答案都表明我需要实例化这个类,或者使它成为静态的。我的类已实例化,我正在尝试访问该实例。谁能看看我的代码,找出哪里出了问题 public class RocketSimMain { public RocketShip test = new RocketShip (); public static void Main() { ... // Do some setup stuf

我很抱歉,我知道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.
        }
    }
}
public class RocketSimMain{
公共火箭艇试验=新火箭艇();
公共静态void Main(){
…//在这里做一些设置工作
//运行游戏循环
而(!EndGameRequested()){

test.Move();为了从静态方法(
Main
)使用它,您必须使
test
静态。

这个问题是因为您试图从静态方法调用非静态类

要解决这个问题,您必须使它们都非静态:

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.
    }
公共火箭艇试验=新火箭艇();
公共图书馆
{
…//在这里做一些设置工作
//运行游戏循环
而(!EndGameRequested())
{

test.Move();
test
不是静态成员变量,但您试图从静态
Main()
test
本身是一个实例字段,不是静态的。您不能从静态上下文中使用它。
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.
    }
}