调用整数数组方法时获取以下内容:索引(从零开始)必须是

Getting the following when invoking an integer array method: Index (zero based) must be

我是第一次学习 c#,我很难理解如何在控制台读数中调用整数数组方法。我正在使用 role-playing 游戏作为设计路线图,在我尝试调用要通过控制台报告的 class 的统计数据之前一直很好。

我正在从这个块中提取数据:

public static int Stats(int[] stats) {
        int str, intel, dex;

        str = 1 * LevelUp();
        intel = 3 * (LevelUp() / 2);
        dex = 2 * (LevelUp() / 3);

        stats[0] = str;
        stats[1] = intel;
        stats[2] = dex;
        return stats[2];
    }

但我在以下控制台读数中收到与标题匹配的错误。

public void HeroStateManager() {
        Mage mage = new Mage();
        Console.ReadLine();
        if (HeroClass() == "Mage") {
            int[] stats = {0,1,2};
            Console.WriteLine("You have the following stats:");
            Console.WriteLine("Intel:   {0}", Mage.Stats(stats));
            Console.WriteLine("Str:     {1}", Mage.Stats(stats));
            Console.WriteLine("Dex:     {2}", Mage.Stats(stats));
        }
    }

我做错了什么?

应该是:

        Console.WriteLine("Intel:   {0}", Mage.Stats(stats));
        Console.WriteLine("Str:     {0}", Mage.Stats(stats));
        Console.WriteLine("Dex:     {0}", Mage.Stats(stats));

像这样更改您的 Stats() 方法:

public static int[] Stats(int[] stats) 
{
    int str, intel, dex;

    str = 1 * LevelUp();
    intel = 3 * (LevelUp() / 2);
    dex = 2 * (LevelUp() / 3);

    stats[0] = str;
    stats[1] = intel;
    stats[2] = dex;
    return stats;
}

你甚至不需要 return 任何东西,因为 int[] 是一个引用类型,但是 return 改变数组可以允许一些流畅的代码。

然后像这样改变另一种方法:

public void HeroStateManager()
{
    Mage mage = new Mage();
    // Console.ReadLine(); what was this? pausing for debugging?

    if (HeroClass() == "Mage")
    {
        int[] stats = new int[3];
        Mage.Stats(stats);

        Console.WriteLine("You have the following stats:");
        Console.WriteLine("Intel:   {0}", stats[0]);
        Console.WriteLine("Str:     {0}", stats[1]);
        Console.WriteLine("Dex:     {0}", stats[2]);
    }
}