【问题标题】:StackOverflowException ErrorStackOverflowException 错误
【发布时间】:2015-10-22 18:27:00
【问题描述】:

我遇到了一个问题,我将我的第一个数组放入了一个名为 DisplayArray1() 的公共方法中,我已经编译了它,当我打开可执行文件时显示“由于 StackOverflowException 而终止进程” ?有没有其他人遇到过这个问题?

这是我目前的代码:

using System;

namespace FlexibleArrayMethod
{
    class Program
    {
        static void Main()
        {
            Console.Clear();

            // Call intDisplayArray1() to output on screen
            intDisplayArray1();
            Console.Write("Array 1:  ");
        }
        public static int intDisplayArray1()
        {
            // first array declaration
            int[] Array1 = {5, 10, 15, 20};

            return intDisplayArray1[];
        }
    }
}

感谢任何帮助!

【问题讨论】:

  • 你是怎么编译的? return intDisplayArray1[]; 无效。
  • 你能解释一下你想达到什么目标吗?
  • 我想你的真实代码是return intDisplayArray1();,但看起来你的意思是return Array1;
  • 我通过命令行编译了所有内容。编译时也没有出现错误,所以老实说我不确定你是否说它无效。我试图创建一个基于控制台的应用程序,它声明了 3 个不同大小的数组。然后将每个数组传递给一个方法,该方法显示每个数组中的所有整数及其总和。
  • @AlyBee 我喜欢你的评论,因为你诚实地说出了你想要的。 :-)

标签: c# arrays methods stack-overflow


【解决方案1】:

假设return intDisplayArray1[];(不能编译)在您的代码中确实是return intDisplayArray1();,那么您就处于递归循环中。

您在没有退出条件的情况下重复调用您的方法。看起来你真的只想返回你的数组:

 public static int[] intDisplayArray1()
 {
    int[] Array1 = { 5, 10, 15, 20 };

    return Array1;
 }

尽管仍然存在大量逻辑错误。

这就是我被引导相信您正在尝试做的事情:

static void Main()
{
    Console.Clear();

    // Call intDisplayArray1() to output on screen
    int[] array1 = intDisplayArray1();
    Console.Write("Array 1: " + string.Join(",", array1));
    Console.Read();
}

public static int[] intDisplayArray1()
{
   // first array declaration
   int[] Array1 = { 5, 10, 15, 20 };

   return Array1;
}

【讨论】:

  • 我编辑了代码,它在命令行中显示了Console.Write("Array 1: ");,但我的数组本身没有显示
  • 我会继续发布我认为您想要的全部内容
  • @AlyBee 不要指望当你编译 Console.Write("Give me coffee: "); 时会做你想做的事。
  • 那么我应该把Console.Write(intDisplayArray());?
  • 您当然可以尝试一下并了解它的作用。最好的学习方式。
猜你喜欢
  • 2021-07-24
  • 1970-01-01
  • 1970-01-01
  • 2019-01-30
  • 1970-01-01
  • 1970-01-01
  • 2021-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多