将锯齿状的对象数组(包含整数和字符串)写入控制台窗口

时间:2013-09-27 14:53:23

标签: c# arrays

这是我的第一个问题,所以如果我违反规则等,我会道歉。

基本上,我有一个包含对象(蠕虫)的锯齿状数组(苹果)。我遇到的主要问题是将此数组的元素写入控制台窗口。我或多或少不明白如何正确索引数组。

        object[][] Apples = new object[2][];   //This says that we will declare a jagged array of objects.  Our Apples array will contain 2 elements, each of which is a single dimensional array

        Apples[0] = new object[2]; //initializing the elements, saying element 0 of apples will be an object, in our case an array, with 2 element
        Apples[1] = new object[2]; //initializing the elements, saying element 1 of apples will be an object, in our case an array, with 2 elements

        Apples[0][0] = new Worm(22, "Matt"); //the first element in the array of worm in the first element of the array of apple
        Apples[0][1] = new Worm(23, "Marty");//the second element in the array of worm in the first element of the array of apple
        Apples[1][0] = new Worm(24, "Mike"); //the first element in the array of worm in the second element of the array of apple
        Apples[1][1] = new Worm(25, "Pete"); //the second element in the array of worm in the second element of the array of apple

        for (int i = 0; i < Apples.Length; i++)  //this is the only thing i'm having trouble with
        {
            for (int j = 0; j < Apples[i].LongLength; j++)
            {
                System.Console.WriteLine("Element[{0}][{1}]: ", i, j);
                System.Console.Write(Apples[i].ToString());
                System.Console.Write("\n\r");
            }
        }
        System.Console.WriteLine("\n\rPress any key to exit.");
        System.Console.ReadKey();

我的蠕虫课程如下:

    public class Worm
{
    public Worm(int WormAge, string WormName) //constructor that accepts two arguments
    {
        int age = WormAge;
        string name = WormName;
    }
}

1 个答案:

答案 0 :(得分:1)

您指的是Worm错误,请尝试使用Apples[i][j]代替Apples[i]

for (int i = 0; i < Apples.Length; i++)  //this is the only thing i'm having trouble with
{
    for (int j = 0; j < Apples[i].LongLength; j++)
    {
        System.Console.WriteLine("Element[{0}][{1}]: ", i, j);
        System.Console.Write(Apples[i][j].ToString());
        System.Console.Write("\n\r");
    }
}

您可能还需要覆盖Worm.ToString(),以便为每个Worm获取更有意义的消息。

public class Worm
{
    // ...

    public override string ToString()
    {
        return string.Format("Worm '{0}', age {1}", name, age);
    }
}