打印列表对象 c# [英] Print list Object c#
问题描述
我正在尝试打印一个对象列表,但只是我的对象名称
hi i trying print a list of object , but just name of my object
班级人物
public class Pessoa
{
public int ID { get; set; }
public int Idade { get; set; }
public string Nome { get; set; }
public List<int> Setor { get; set; }
}
我的主课
static void Main(string[] args){
static void Main(string[] args) {
List<Pessoa> pessoas = new List<Pessoa>();
pessoas.Add(new Pessoa
{
ID = 2,
Idade = 32,
Nome = "name",
Setor = new List<int> { 2, 55, 32, 13, 24 }
});
pessoas.Add(
new Pessoa
{
ID = 12,
Idade = 24,
Nome = "name",
Setor = new List<int> { 2, 55, 32 }
});
pessoas.Add(
new Pessoa
{
ID = 19,
Idade = 29,
Nome = "name",
Setor = new List<int> { 2, 32 }
});
var teste = new Pessoa();
foreach (var p in pessoas)
{
Console.WriteLine(p);
}
Console.ReadKey();
}
返回一个空列表返回一个空列表返回一个空列表返回一个空列表返回一个空列表
return a list empty return a list empty return a list empty return a list empty return a list empty
推荐答案
打印用户定义的对象不会以这种方式工作.正如您在 Console.WriteLine 调用对象的ToString()"方法进行打印,标准实现打印该对象的类名.
Printing a user defined object will not work this way. As you could read in the documentation of Console.WriteLine it calls the "ToString()" method of the object to print and the standard implementation prints the name of the class of this object.
如果您想输出对象的内容,您必须覆盖 ToString() 方法.
If you want to output the contents of your object you have to override the ToString() method.
示例:
public class Pessoa {
....
override ToString() {
return $"ID = {ID}, IIdade = {Idade}, ....";
}
}
这篇关于打印列表对象 c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!