我想按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));
}
我试图列出(main)的列表,但我不知道。
答案 0 :(得分:0)
尝试这样的事情:
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
}
答案 1 :(得分:-1)
使用此
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();
}