如何在类方法中填充矩阵?

时间:2015-08-12 09:44:06

标签: c# arrays class methods

我创建了一个班级Matrix。我创建了一个填充矩阵的方法,我有一个错误。有什么问题?

class Matrix
{
    private static int n, m;
    private string[,] arr = new string[n, m];
    public int N
    {
        set 
        {
            n = value;
        }
        get
        {
            return n;
        }
    }
    public int M
    {
        set
        {
            m = value;
        }
        get
        {
            return m;
        }
    }

    public string[,] SetMatrix()
    {
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                arr[i, j] = Console.ReadLine();
            }
        }
        return arr;
    }
}


static void Main(string[] args)
{
    Matrix matrix = new Matrix();

    Console.WriteLine("- enter n");
    matrix.N = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine("- enter m");
    matrix.M = Convert.ToInt32(Console.ReadLine());
    string[,] arr= new string[matrix.N, matrix.M];
    Console.WriteLine("enter matrix data");

    arr = matrix.SetMatrix(); //Error at this line

    Console.ReadKey();    
}

错误: An unhandled exception of type "System.IndexOutOfRangeException" in Matrix.exe

有关详细信息:Index was outside the bounds of the array.

提前致谢。

1 个答案:

答案 0 :(得分:1)

您没有在构造函数中设置arr数组。通过使用默认的n和m值,您的arr数组始终为0行和0列。这就是indexOutOfRange即将到来的原因。

你可以使用像这样的构造函数来解决这个问题 -

public Matrix(int _n, int _m)
{
    n = _n;
    m = _m;
    arr = new string[n,m];
}