[英]How to display the contents of a class which is generic list, by foreach loop?
I want to display the contents of collection in list by foreach loop but variables (name) and (age) do not match in foreach loop. 我想按foreach循环在列表中显示集合的内容,但变量(name)和(age)在foreach循环中不匹配。
string name;
float age;
List<universe> collection = new List<universe>();
universe main = new universe();
for (int i = 0; i < 10; i++)
{
Console.WriteLine("name");
name = Console.ReadLine();
Console.WriteLine("age");
age = float.Parse(Console.ReadLine());
main.Galaxy(name, age);
collection.Add(main);
}
foreach (universe b in collection)
{
Console.WriteLine(main.Galaxy(name, age));
}
I've tried to make a list of (main) but I coudn't. 我试过列出(主要)清单,但我不知道。
Try something like this: 尝试这样的事情:
string name;
float age;
List<universe> collection = new List<universe>();
for (int i = 0; i < 10; i++)
{
universe main = new universe();
Console.WriteLine("name");
name = Console.ReadLine();
Console.WriteLine("age");
age = float.Parse(Console.ReadLine());
main.Galaxy(name, age);
collection.Add(main);
}
foreach (universe b in collection)
{
Console.WriteLine($"{b.Name} {b.Age}"); // <== I don't know if universe class has Name and Age properties
}
Use this 用这个
static void Main(string[] args)
{
string name;
float age;
List<universe> collection = new List<universe>();
universe main = new universe();
for (int i = 0; i < 2; i++)
{
Console.WriteLine("name");
name = Console.ReadLine();
Console.WriteLine("age");
age = float.Parse(Console.ReadLine());
main.Galaxy(name, age);
collection.Add(main);
}
foreach (universe b in collection)
{
Console.WriteLine("name =" + b.Name + " Age=" + b.Age);
}
Console.ReadKey();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.