我试图在主要范围内使用foreach
循环打印我的列表中的对象元素,但唯一打印出来的是:
ConsoleApplication1.WorldMap
这里出了什么问题,如何打印实际元素?
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);
}
}
}
}
答案 0 :(得分:2)
因为您没有覆盖ToString
的{{1}}方法,所以WorldMap
会返回Console.WriteLine(view)
类的名称。您可以覆盖类中的WorldMap
方法或调用ToString
循环中的属性,但不要忘记您应该将foreach
更改为object
。像这样:
var
或(将class WorldMap
{
....
....
public override string ToString()
{
return Lower + " " + Higher;
}
}
更改为object
):
var
答案 1 :(得分:0)
视图是WorldMap类型,请改为使用它:
foreach (object view in mapList)
{
Console.WriteLine(view.Lower.ToString() + "," + view.Higher.ToString() );
}