如何打印具有属性的对象列表?

时间:2019-10-14 08:07:26

标签: c# list object

我是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);
}

1 个答案:

答案 0 :(得分:2)

首先,让每个类(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());
 }