【问题标题】:C# global array won't workC# 全局数组不起作用
【发布时间】:2017-09-04 09:28:53
【问题描述】:

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

我收到错误消息:

'GAArr' 在当前上下文中不存在

详情请参见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 类,但是(据我了解)这将花费大量时间并且使访问和操作实例的位置变得更加困难。 请帮忙。

【问题讨论】:

  • 您在代码中的“所说的数组”不是全局的......把它放在 world 之外但在类里面。
  • 全局变量范围仅限于类级别。
  • 每次调用 Update() 时都要重新创建数组,所以它不起作用
  • 定义“不起作用”?你会得到什么结果,你会得到什么结果?
  • 需要在方法外声明数组。

标签: c# arrays class global


【解决方案1】:

GAArr 被定义为World() 方法中的本地 变量。它不能从嵌套的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的构造函数
  • 将数组定义为静态类中的单例,并引用它。

【讨论】:

  • 感谢您的快速回复,但我已经明白了。我只是不知道如何让它全球化
  • 只在函数外声明它,但在类内
  • @Mr.Dude__ 我添加了更多细节,看看。
【解决方案2】:

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

首先,制作如下类。

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

那么在你的世界级改变中

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

进入这个

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

在墙类中

 void Draw() {
        Globals.GAArr[x, y] = "#";
    }

【讨论】:

    【解决方案3】:
    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
        }
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-13
      • 1970-01-01
      • 1970-01-01
      • 2016-12-30
      相关资源
      最近更新 更多