【问题标题】:Pass reference array as argument in c# [duplicate]在c#中将引用数组作为参数传递[重复]
【发布时间】:2023-04-05 15:53:01
【问题描述】:

亲爱的,

我创建了一个方法,该方法将在使用 ref 选项填充三个数组后检索它们

出现以下错误“System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'”

代码如下。我该如何解决它

 namespace ConsoleApp9
{
    class Program
    {
        public static int getarrays(ref string[] patternName, ref int[] loadindex, ref double[] loadFactor)
        {
            int status = 0;
            for (int i = 0; i < 4; i++)
            {
                patternName[i] = "test";
            }
            for (int i = 0; i < 5; i++)
            {
                loadindex[i] = i;
            }
            for (int i = 0; i < 8; i++)
            {
                loadFactor[i] = i/10;
            }
            return status;
        }
        static void Main(string[] args)
        {
            string[] ptt = new string[1];
            int[] index = new int[1];
            double[] factor = new double[1];
            getarrays(ref ptt,ref index, ref factor);
        }
    }

}

【问题讨论】:

    标签: c# arrays arguments ref


    【解决方案1】:

    您正在传递固定大小为1 的数组。在您的方法中,您将迭代 4、5 和 8 次,而您的 arrays 的长度为 1。您应该创建 pttSizeindexSizefactorSize 的常量并将它们用作 arrays 大小和loops 长度。

    【讨论】:

      【解决方案2】:

      您将长度为 1 的数组传递给函数,然后尝试访问大于 0 的索引。

      调整您的 Main 方法以传递正确长度的数组:

      string[] ptt = new string[4];
      int[] index = new int[5];
      double[] factor = new double[8];
      

      【讨论】:

        【解决方案3】:

        您的数组的大小均为 1,但您的循环分别为 4、5 和 8。相反,请在循环中使用数组的 Length 属性:

        for (int i = 0; i < patternName.Length; i++)
        {
            patternName[i] = "test";
        }
        

        这很有帮助,因为数组的大小只位于一个位置(在创建数组时)。

        【讨论】:

          猜你喜欢
          • 2013-07-24
          • 1970-01-01
          • 2023-03-03
          • 1970-01-01
          • 2011-04-07
          • 2017-02-12
          • 2017-03-19
          • 2011-12-30
          相关资源
          最近更新 更多