从列表中打印出对象元素 [英] Print out object elements from list
问题描述
我正尝试在主作用域中使用 foreach
循环在列表中打印对象元素,但唯一打印出的内容是:
I'm trying to print object element in my list with foreach
loop in main scope, but the only thing that prints out is :
ConsoleApplication1.WorldMap
ConsoleApplication1.WorldMap
这里出了什么问题?如何打印出实际的元素?
What have gone wrong here and how do I get it to print out the actual elements?
using ConsoleApplication1;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class WorldMap
{
private string higher;
private string lower;
public worldMap()
{
}
public WorldMap(string higher, string lower)
{
this.higher = higher;
this.lower = lower;
}
public string Higher
{
get { return higher; }
set { higher = value; }
}
public string Lower
{
get { return Lower; }
set { Lower = value; }
}
}
class Program
{
static void Main(string[] args)
{
WorldMap map = new WorldMap();
List<WorldMap> mapList = new List<WorldMap>();
mapList.Add(new WorldMap(map.Lower, map.Higher));
Console.WriteLine("\tInsert highest point:");
map.Highest= Console.ReadLine();
Console.WriteLine("\tInsert lowest point");
map.Lowest= Console.ReadLine();
using (StreamWriter writer = new StreamWriter(@"C:\freq.txt", true))
{
writer.WriteLine(map.Lower + map.Higher);
}
foreach (object view in mapList)
{
Console.WriteLine(view);
}
}
}
}
推荐答案
因为您没有覆盖 WorldMap
的 ToString
方法,所以 Console.WriteLine(视图)
返回该类的名称,即 WorldMap
.您可以覆盖类中的 ToString
方法,也可以在 foreach
循环中调用属性,但不要忘记,您应该将 object
更改为 var
.像这样:
Because you didn't override the ToString
method of WorldMap
so Console.WriteLine(view)
returns the name of the class which is WorldMap
. You could either override the ToString
method in the class or call the properties in the foreach
loop but don't forget you should change object
to var
. Like this:
class WorldMap
{
....
....
public override string ToString()
{
return Lower + " " + Higher;
}
}
或(将 object
更改为 var
):
Or (change object
to var
):
foreach (var view in mapList)
{
Console.WriteLine(view.Lower + " " + view.Higher);
}
这篇关于从列表中打印出对象元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!