C# 全局数组不起作用

标签 c# arrays class global

我是 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
    }
}

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

最佳答案

GAArrWorld() 方法中被定义为一个本地变量。它不能从嵌套的 Wall 类的范围内访问。

您可能会发现这很有用: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;
        }
    }
}

其他一些答案建议您将数组作为父类的成员。这也不起作用:

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 的构造函数
  • 将数组定义为静态类中的单例,并引用它。

关于C# 全局数组不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46034116/

相关文章:

c# - 在移动设备上运行时更改 Gridview 列的可见性?

c# - XUnit.net 在运行后立即捕获每个测试的结果

c# - 将 Double 转换为 Short 到 Byte

javascript - JS 中的函数,返回一个对象,该对象在数组中具有唯一值以及它们出现的次数

c# - 如何在初始化时插入数组条目?

c++ - <function> 不是 <class> 的成员

C++: 不匹配调用 '(concat) (std::string&)'

Java:返回一个类User,与更改它相同吗?

c# - 尝试在 sql server 中插入日期和时间但出现错误

c# - Unity3D连接MySQL报错