问题
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