打印列表对象c# [英] Print list Object c#

查看:69
本文介绍了打印列表对象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

推荐答案

打印用户定义的对象将无法通过这种方式进行.如您在

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆