【问题标题】:How to print a list of objects with properties? [duplicate]如何打印具有属性的对象列表? [复制]
【发布时间】:2019-10-14 16:58:55
【问题描述】:

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

【问题讨论】:

  • 你能显示你想要的输出吗?
  • @Sweeper 我要打印在 Dipendente 中定义的 Id、nome、cognome、tipocontratto
  • 你不能打印dip.Iddip.Nomedip.Cognome等吗?
  • @Sweeper 我必须从列表中打印出来
  • 只需覆盖类中的ToString 方法并为其提供实现,然后在每个循环中调用它

标签: c# list object


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2023-01-11
    • 2019-01-31
    • 2015-08-09
    • 1970-01-01
    • 2011-03-03
    • 1970-01-01
    • 2014-12-19
    • 1970-01-01
    • 2010-10-25
    相关资源
    最近更新 更多