【问题标题】:How Do I Print An Array With Attributes?如何打印带有属性的数组?
【发布时间】:2016-03-21 00:03:35
【问题描述】:

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

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 等,而且我不知道如何修复代码。它说在那种情况下不存在扩展?所以我不确定...

【问题讨论】:

  • 我想你想用animal[]而不是int[]
  • 这个循环在一个单独的方法中,而不是在 main.js 中的其他代码。我打算在 main 中调用这个函数并引用动物数组,但这并不能解决问题
  • 你试过这个...public static void printarray2 (animal[] A) ?
  • 这似乎也不起作用
  • A 上面的代码中是一个不具有.name 和.weight 等属性的整数数组。它应该是一组动物来访问这些属性。如果您在方法名称中更改它,您还需要将传入的内容更改为动物数组。

标签: c# arrays loops attributes


【解决方案1】:

试试这个...

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。还将循环中的硬编码 5 替换为 A.Length

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-09
    • 2011-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    相关资源
    最近更新 更多