print list<object> in console c# [duplicate]

橙三吉。 提交于 2021-02-11 07:47:29

问题


when i try to print a list of objects in c# it does not print what i want, let me demonstrate.

example:

public class Classname
    {
        public string hello;
        public string world;

        
    }

namespace inloggning
{

    class Program
    {
        static void Main(string[] args)
        {
            List<object> listOfObjects = new List<object>();

            Classname example = new Classname();
            example.hello = "hello";
            example.world = "world";

            listOfObjects.Add(example);

            Console.WriteLine(listOfObjects[0]);

        }

    }
}

when i run this it prints out "inloggning.Classname". Can someone help me understand why and how i can fix it so it prints "hello" and "world".


回答1:


Add a toString method to your object, like that

public string overide ToString()
{
return hello + " " + world;
}

EDIT: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-override-the-tostring-method




回答2:


Change the WriteLine statement like this:

Console.WriteLine(((ClassName)listOfObjects[0]).hello+(ClassName)listOfObjects[0]).world);



来源:https://stackoverflow.com/questions/63196618/print-listobject-in-console-c-sharp

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