首页 > 解决方案 > 如何打印具有属性的对象列表?

问题描述

我是 C# 的初学者,我有这门课:

public Dipendente(String Id, String Nome, String Cognome, Contratto TipoContratto, DateTime Data_assunzione, double Stipendio, Dipendente Tutor)
{
    this.Id = Id;
    this.Nome = Nome;
    this.Cognome = Cognome;
    this.TipoContratto = TipoContratto;
    this.DataAssunzione = Data_assunzione;
    this.StipendioMensile = Stipendio;
    this.Tutor = Tutor;
}

public static Dipendente GetDipendenteFromPersona(Persona persona, Contratto contratto, DateTime data_assunzione, double stipendio, Dipendente tutor)
{
    Dipendente result = null;
    result = new Dipendente(persona.Id, persona.Nome, persona.Cognome, contratto, data_assunzione, stipendio, tutor);
    return result;
}

我主要有一个这样的对象列表:

Dipendente dip1 = Dipendente.GetDipendenteFromPersona(p1, lstContratti[1], new DateTime(2000, 10, 10), 1000, null);
List<Dipendente> lstDipendenti = new List<Dipendente> {dip1, dip2, dip3, dip4, dip5, dip6, dip7, dip8};

我需要用他的属性打印列表中的每个项目,这是最好的方法吗?

我已经尝试过了,但显然没有得到属性值:

foreach (Dipendente dip in lstDipendenti)
{
    System.Diagnostics.Debug.WriteLine(dip);
}

标签: c#listobject

解决方案


首先,让每个类 ( Dipendente) 实例为自己说话.ToString()就是这样做的地方:

返回表示当前对象的字符串。

...它将对象转换为其字符串表示形式,以便它适合显示...

 public class Dipendente 
 {
     ...

     public override string ToString() 
     {  
         // Put here all the fields / properties you mant to see in the desired format
         // Here we have "Id = 123; Nome = John; Cognome = Smith" format
         return string.Join("; ",
           $"Id = {Id}",
           $"Nome = {Nome}", 
           $"Cognome = {Cognome}"  
         );
     }
 }

然后你可以把

 foreach (Dipendente dip in lstDipendenti)
 {
     // Or even System.Diagnostics.Debug.WriteLine(dip);
     System.Diagnostics.Debug.WriteLine(dip.ToString());
 }

推荐阅读