问题
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
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);
}
}
}
}
回答1:
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;
}
}
Or (change object
to var
):
foreach (var view in mapList)
{
Console.WriteLine(view.Lower + " " + view.Higher);
}
回答2:
view is of type WorldMap, Use it like this instead:
foreach (object view in mapList)
{
Console.WriteLine(view.Lower.ToString() + "," + view.Higher.ToString() );
}
来源:https://stackoverflow.com/questions/35957637/print-out-object-elements-from-list