【问题标题】:I got a problem with a simple List in C#(not displaying the actually list)我在 C# 中遇到了一个简单列表的问题(不显示实际列表)
【发布时间】:2019-06-11 04:01:53
【问题描述】:
List<int> MyList = new List<int>();
MyList.Add(1);
MyList.Add(2);
MyList.Add(3);
MyList.Add(4);
foreach(int item in MyList){
    System.Console.WriteLine(MyList);
}

这是我的代码显示的内容:

System.Collections.Generic.List`1[System.Int32]
System.Collections.Generic.List`1[System.Int32]
System.Collections.Generic.List`1[System.Int32]
System.Collections.Generic.List`1[System.Int32]

【问题讨论】:

  • 只打印号码:System.Console.WriteLine(item);
  • 您对列表中的每个“项目”都有一个循环,因此您需要处理项目,而不是“我的列表”。打印项目而不是 'MyList'
  • 您正在使用 foreach 显示列表对象,但您尝试编写列表对象.. 更改 System.Console.WriteLine(MyList);到 System.Console.WriteLine(item);

标签: c#


【解决方案1】:

当你 ToString 一个对象(这是 Console.WriteLine 所做的),并且它没有覆盖 ToString() 时,它会写入类的名称。但是,您可以只使用item,这看起来像一个简单的错误

var myList = new List<int> { 1, 2, 3, 4 };

foreach (var item in myList)
   System.Console.WriteLine(item);

// or, you can get fancy with string.Join

Console.WriteLine(string.Join(", ", myList));

【讨论】:

    【解决方案2】:

    您需要将MyList 更改为item 以显示MyList 变量中的每个项目。

    foreach(int item in MyList){
        System.Console.WriteLine(item);
        }
    

    【讨论】:

      猜你喜欢
      • 2021-04-20
      • 1970-01-01
      • 1970-01-01
      • 2023-02-05
      • 2021-06-11
      • 2020-06-12
      • 2021-01-07
      • 1970-01-01
      相关资源
      最近更新 更多