0

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

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

        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;
    }
}
4

1 回答 1

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);
    }
}
于 2013-09-27T14:56:11.293 回答