C# 全局数组不起作用

C# global array won't work

我是 C# 的新手,但我正在尝试制作一个简单的游戏。为了使实例的移动和定位变得容易,我使用了一个数组。问题是我似乎无法让它工作。

我收到错误消息:

'GAArr' doesn't exist in the current context

有关详细信息,请参阅 Draw 方法。

//Every part of the world: terrain, enemies, itmes and alike
static void World()
{
    int GAWidth = 78;
    int GAHeight = 25;
    string[,] GAArr = new string[GAWidth, GAHeight]; //said array
    ...
}


//Wall class
class Wall {
    ...

    public Wall(int x, int y, int mh){
        ...
    }

    void Draw() {
        GAArr[x, y] = "#"; //it says the name 'GAArr' doesn't exist in the current context
    }
}

(很抱歉复制了所有代码,但这可能会让我更清楚我想做什么) 我已经尝试了一些解决方案,例如创建静态全局 class,但这似乎没有用。我看到的另一件事是拍卖 class,但是(据我了解)这会花费很多时间并且使访问和操纵实例的位置变得更加困难。 请帮忙。

GAArrWorld() 方法中定义为 local 变量。它不能从嵌套 Wall class 的范围访问。

您可能会发现这很有用:C# Language specification - Scopes


这是您尝试执行的操作的一个更简单的示例:

public class Outer
{
    public void Draw()
    {
        int[] intArray = new[] { 1, 2, 3 };
    }

    public class Inner
    {
        public void Draw()
        {
            // ERROR: The defined array is not available in this scope.
            intArray[0] = 0;
        }
    }
}

其他一些答案建议您将数组作为父数组的成员 class。那也不管用:

public class Outer
{
    public int[] IntArray = new[] { 1, 2, 3 };

    public class Inner
    {
        public void Draw()
        {
            // ERROR: As the nested class can be instantiated without its parent, it has no way to reference this member.
            IntArray[0] = 0;
        }
    }
}

您可以通过多种方式解决此问题,包括:

  • 将数组作为参数传递给Wall.Draw()方法,甚至传递给Wall的构造函数
  • 将数组定义为静态 class 中的单例,并引用它。

您的变量只能在 class 的范围内访问。要使其他 classes 可以访问变量,您必须提供引用(例如,在构造函数中)或使 class 将保存此变量

首先,制作class如下。

static class Globals
{
    public static string[,] GAArr; //Maybe needed to initialize, I dont have access to Vs atm so only I only guess syntax 
}

那么在你的世界class改变

string[,] GAArr = new string[GAWidth, GAHeight]; //said array

进入这个

Globals.GAArr = new string[GAWidth, GAHeight]; //said array

在墙上 class

 void Draw() {
        Globals.GAArr[x, y] = "#";
    }
class Program
{
    static string[,] GAArr; // define in the class, but outside of the functions
    // ...
    static void World()
    {
        // ...
        GAArr = new string[GAWidth, GAHeight]; // create
        // ...
    }
    // ...
}

class Wall
{
    void Draw()
    {
        Program.GAArr[x,y] ? "#"; // Use in another class
    }
}

请注意,在初始化之前每次使用数组都会导致异常。