0

这是我的代码:

namespace Exercise6
{
    class Program
    {
        static void Main(string[] args)
        {

            OtherClass aTable = new OtherClass(); //instantiate class

            Console.WriteLine("How many rows do you want your two-dimensional array to be?");
            aTable.SRows = Console.ReadLine(); //reads input for how many rows that the user would like
            aTable.IntRows = int.Parse(aTable.SRows); //convert rows to int

            Console.WriteLine("Thanks you! How many columns would you like your two-dimensional arry to be?");
            aTable.SColumns = Console.ReadLine(); //reads input for how many columns that the user would like
            aTable.IntColumns = int.Parse(aTable.SColumns); //convert columns to int

            //set two dimensional array based upon the size that the user has requested

            int[ , ] array = new int[aTable.IntColumns, aTable.IntRows];

            Random randomArray = new Random(); //call to random class to ask for random numbers

            for (int i = 0; i < aTable.IntColumns; i++) //columns
            {
                array[i, 0] = randomArray.Next(0, 100); //for every value in each column, insert a random number
            }

            for (int y = 0; y < aTable.IntRows; y++) //rows
            {
                array[y, 0] = randomArray.Next(0, 100);
            }

            Console.WriteLine(array);


        }
    }
}

namespace Exercise6
{
    class OtherClass
    {
        private string sRows;

        public string SRows { get; set; }

        private int intRows;

        public int IntRows { get; set; }

        private string sColumns;

        public string SColumns { get; set; }

        private int intColumns;

        public int IntColumns { get; set; }

    }
}

但是,我无法弄清楚为什么我的输出(应该只是我的数组)会说:

System.Int32[,]

它没有将 for 循环中的随机数添加到我的数组中吗?

提前感谢您的所有帮助!

4

4 回答 4

4

当您调用 时Console.WriteLine(array),它会调用array'ToString方法。由于数组没有提供更好的实现,所以调用默认值ToString,它只返回它的类型:System.Int32[,]。您需要指定自己如何将该数组转换为 a string,例如

for (int i = 0; i < aTable.IntColumns; i++)
{
    for (int j = 0; j < aTable.IntRows; j++)
    {
        if (j != 0)
            Console.Write(", ");
        Console.Write(array[i, j]);
    }
    Console.WriteLine();
}

写类似:

0, 1, 2
3, 4, 5
于 2013-10-16T18:05:07.233 回答
2

我相信您的实际问题是:为什么ToString大多数类型只返回类型名称,而不是String.ToString返回值。

大多数类不会覆盖ToString方法,因此会获得默认行为,即输出类型名称。

在您的特定情况下,您可能希望遍历所有元素并打印它们。

于 2013-10-16T18:04:56.617 回答
1

Console.WriteLine(array); 正在调用 array.ToString()。默认情况下,这是打印对象类型。

返回表示当前对象的字符串。(继承自对象。)

阵列 MSDN

您需要手动给出数组的每个条目。这可以通过循环来完成,有关示例,请参阅链接文章。

于 2013-10-16T18:03:09.643 回答
0

这是因为您正在编写Array对象。您需要将数组中的每个单独元素写出,或ToString()在数组中覆盖。

于 2013-10-16T18:01:24.147 回答