从列表中打印出对象元素

时间:2016-03-12 12:28:52

标签: c# console-application

我试图在主要范围内使用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);
        }
      }
   }
}

2 个答案:

答案 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() );
        }