【发布时间】:2020-12-17 13:15:10
【问题描述】:
我有一个对象列表。我现在想把列表放在前面,但也要像这样在前面添加数字......
1] 项[0]
2] 项目[1]
3] 项目[2]
我有这个功能
private void ListAnimals()
{
foreach (var pet in _petslist)
{
Console.WriteLine(pet);
}
}
然后我像这样调用那个函数
public void Play()
{
Console.WriteLine("You have these pets in your list...");
ListAnimals();
Console.WriteLine("Which pet would you like to play with?");
string input = Console.ReadLine().ToLower();
switch (input)
{
case "pet1":
_petslist[0].Interact();
break;
case "pet2":
_petslist[1].Interact();
break;
case "pet3":
_petslist[2].Interact();
break;
default:
Console.WriteLine("You do not own that pet, please try again");
break;
}
}
我的问题,我可以在我的 ListAnimals() 函数中以某种方式在列表项前面显示数字,以便我可以在 switch 语句中使用该数字而不是实际的宠物名称吗?我试图在我的动物类中覆盖 ToString(),我尝试过填充,还尝试添加一个数字数组并使用 for 循环输出数组中的数字并列出彼此靠近的项目。
【问题讨论】:
-
要么使用for循环而不是foreach来获取列表索引,要么使用
foreach ((i, pet) in petslist.Select(var (i, pet) => (i, pet))。然后Console.WriteLine($"{i + 1}] {pet}");