如何打印带属性的数组?

时间:2016-03-21 00:03:36

标签: c# arrays loops attributes

到目前为止我有这个代码......我创建了一个这样的数组:

namespace animal_array
{

    class Program
    {

        struct animal
        {

            public string Name;

            public string Color;

            public int Weight;

            public int Age;
        }

        static void Main(string[] args)
        {

            int[] Array = new int[5];
            animal cat;
            cat.name = "cat";
            cat.age = 2;
            cat.weight = 10;
            cat.color = "black";

我为其他四只动物做同样的事情...... 然后我需要一个打印出所有动物信息的循环,我认为它会是这样的:

public static void printarray2 (int[] A) //print array function
{

    for (int i = 0; i< 5; i++)
    {
        Console.WriteLine ("Name: " + A[i].name);
        Console.WriteLine("Weight: " + A[i].weight);
        Console.WriteLine("Age: " + A[i].age);
        Console.WriteLine("Color: " + A[i].color);
    }
}

但它不允许我使用.name,.color等,而且我不知道如何修复代码。它说扩展不存在于这种情况下?所以我不确定......

1 个答案:

答案 0 :(得分:2)

试试这个......

public class Program
{

    // Animal
    public struct Animal
    {
        public string Name;
        public string Color;
        public int Weight;
        public int Age;
    }

    // Main
    public static void Main(string[] args)
    {
        Animal[] animals = new Animal[5];

        animals[0] = new Animal { Name = "Cat", Color = "Grey", Weight = 20, Age = 7  };
        animals[1] = new Animal { Name = "Dog", Color = "Grey", Weight = 20, Age = 7 };
        animals[2] = new Animal { Name = "Horse", Color = "Grey", Weight = 20, Age = 7 };
        animals[3] = new Animal { Name = "Rabbit", Color = "Grey", Weight = 20, Age = 7 };
        animals[4] = new Animal { Name = "Mouse", Color = "Grey", Weight = 20, Age = 7 };

        OutputAnimals(animals);
    }

    // Print out animals
    public static void OutputAnimals(Animal[] A)
    {

        for (int i = 0; i < A.Length; i++)
        {
            Console.WriteLine("Name: " + A[i].Name);
            Console.WriteLine("Weight: " + A[i].Weight);
            Console.WriteLine("Age: " + A[i].Age);
            Console.WriteLine("Color: " + A[i].Color);
        }

    }
}

它正在使用Animal而不是int的数组,并修复了属性的大小写,例如.name变为.Name。还用A.Length替换了循环中的硬编码5。