Print out object elements from list

浪子不回头ぞ 提交于 2021-01-13 09:13:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!