Как распечатать список объектов со свойствами? - PullRequest
0 голосов
/ 14 октября 2019

Я новичок в 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 Ответ

2 голосов
/ 14 октября 2019

Во-первых, пусть каждый экземпляр класса (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());
 }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...