[英]How to properly print the content of a list in C#
I have created a small console application to test some stuff with collections.我创建了一个小的控制台应用程序来测试一些带有集合的东西。
My code looks like this:我的代码如下所示:
namespace Collections
{
class Program
{
static void Main(string[] args)
{
List<string> cars = new List<string>();
cars.Add("BMW"); //0
cars.Add("Tesla"); //1
//Add Honda here
cars.Add("Audi"); //2
cars.Add("Ford"); //3
cars.Insert(2, "Honda");
foreach(string car in cars)
{
Console.WriteLine(cars);
}
//Console.Read();
}
}
}
I expect the output to be我希望输出是
BMW
宝马
Tesla特斯拉
Honda本田
Audi奥迪
Ford福特
But my output actually looks like this但我的输出实际上是这样的
System.Collections.Generic.List`1[System.String] System.Collections.Generic.List`1[System.String] System.Collections.Generic.List`1[System.String] System.Collections.Generic.List`1[System.String] System.Collections.Generic.List`1[System.String]
System.Collections.Generic.List`1[System.String] System.Collections.Generic.List`1[System.String] System.Collections.Generic.List`1[System.String] System.Collections.Generic.List` 1[System.String] System.Collections.Generic.List`1[System.String]
But I can't find my mistake here.但我在这里找不到我的错误。
You're printing cars
- the collection - instead of car
- the current iteration.您正在打印
cars
- 集合 - 而不是car
- 当前迭代。 Change it to Console.WriteLine(car);
将其更改为
Console.WriteLine(car);
. .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.