C# 如何打印具有属性的数组?
到目前为止,我已经有了这段代码…我创建了一个如下的数组:C# 如何打印具有属性的数组?,c#,arrays,loops,attributes,C#,Arrays,Loops,Attributes,到目前为止,我已经有了这段代码…我创建了一个如下的数组: namespace animal_array { class Program { struct animal { public string Name; public string Color; public int Weight; public int Age; }
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);
}
}
publicstaticvoidprintary2(int[]A)//打印数组函数
{
对于(int i=0;i<5;i++)
{
Console.WriteLine(“Name:+A[i].Name”);
Console.WriteLine(“重量:+A[i].Weight);
Console.WriteLine(“年龄:+A[i].Age);
Console.WriteLine(“Color:+A[i].Color”);
}
}
但它不允许我做.name、.color等操作,而且我不知道如何修复代码。它说扩展在那个上下文中不存在?所以我不确定…试试这个
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);
}
}
}
公共类程序
{
//畜生
公共结构动物
{
公共字符串名称;
公共字符串颜色;
公共权重;
公共信息;
}
//主要
公共静态void Main(字符串[]args)
{
动物[]动物=新动物[5];
动物[0]=新动物{Name=“Cat”,Color=“Grey”,体重=20,年龄=7};
动物[1]=新动物{Name=“Dog”,Color=“Grey”,体重=20,年龄=7};
动物[2]=新动物{Name=“Horse”,Color=“Grey”,体重=20,年龄=7};
动物[3]=新动物{Name=“兔子”,Color=“灰色”,体重=20,年龄=7};
动物[4]=新动物{Name=“Mouse”,Color=“Grey”,体重=20,年龄=7};
输出动物(动物);
}
//打印动物
公共静态空洞输出动物(动物[]A)
{
for(int i=0;i
它使用了
Animal
数组,而不是int
,并修复了属性的大小写,例如.name
变成.name
。还将循环中的硬编码5替换为A.Length
我认为您希望使用animal[]
而不是int[]
此循环与主循环中的其他代码采用单独的方法。我打算在main中调用这个函数并引用animal数组,但这并不能解决问题。您是否尝试过这个publicstaticvoidprintary2(animal[]A)
?这似乎不起作用在上面的代码中A
是一个整数数组,它没有.name和.weight等属性。它应该是一组动物来访问这些属性。如果在方法名中更改它,还需要将传入的内容更改为动物数组。