C#中的多维数组,IndexOutOfRange异常

时间:2017-02-18 00:45:34

标签: c# arrays multidimensional-array indexoutofrangeexception

我正在学习C#(来自Ruby),并决定深入研究多维数组。为此,我决定使用C#解决“图像模糊”问题。这包括找到多阵列中的所有“1”,并将“1”的上方,下方,右侧和左侧的所有值更改为“1”。

例如:

0000
0010
0000
0000

应该变成:

0010
0111
0010
0000

在我的blur(int[,])方法(第26行)中,我得到IndexOutOfRangeException。我不确定为什么,因为据我所知,我试图修改的point是在数组的范围内。有人可以帮帮我吗?

提前致谢!

using System;


/* For every topic that I had to research, I wrote a REF down below (at the end of the
 * document). They are all numbered and have a link to the resource. */

namespace ImageBlurCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            int[,] multiarray =     { { 0, 0, 0, 0 },
                                      { 2, 0, 1, 0 },
                                      { 3, 0, 0, 0 },
                                      { 4, 0, 0, 0 } };


            Blur(multiarray);


            OutputArray(multiarray);
            Console.ReadLine();
        }

        public static void Blur(int[,] multiarray)
        {
            int[,] blurredArray = multiarray;

            for (int row = 0; row < multiarray.GetLength(0); row++)
            {
                for (int col = 0; col < multiarray.GetLength(1); col++)
                {
                    int point = multiarray[row, col];

                    if (point == 1)
                    {
                        blurredArray[row - 1, col] = 1;
                        blurredArray[row + 1, col] = 1;
                        blurredArray[row, col - 1] = 1;
                        blurredArray[row, col + 1] = 1;
                    };

                }
                OutputArray(blurredArray);
            }
        }

        // Method outputs 2d array to the console.
        static void OutputArray(int[,] multiarray)
        {
            // REF#1 - Difference between .GetLength() and .Length()
            for (int row = 0; row < multiarray.GetLength(0); row++)
            {
                for (int col = 0; col < multiarray.GetLength(1); col++)
                {
                    int s = multiarray[row, col];
                    Console.Write(s);
                }
                Console.WriteLine("");
            }
        }


    }
}


/* REF:
    - Difference between Array.GetLength() and Array.Length():
    http://stackoverflow.com/questions/2044591/what-is-the-difference-between-array-getlength-and-array-length

*/

0 个答案:

没有答案