c# object to string to display it in text format

别说谁变了你拦得住时间么 提交于 2020-01-04 05:53:29

问题


I have the next object/list "ListaDatos" and I like to get it as clear string (to visualize/send this via mail, etc)

public List<Datos> ListaDatos = new List<Datos>();

public class Datos
{
    public string Numero;
    public string Alias;
    public string URLConsumo;

    //-- Consumos ----------------------------- 
    public List<Consumo> Consumos = new List<Consumo>();
    public string ConsumoTotal;
}

public class Consumo 
{
    public string Tipo;
    public string Subtipo;
    public string Concepto;
    public string Cantidad;
    public string Importe;
    public string Total;
}

What is the easiest way to "render" this object into text to obtain a string variable with something like this:

DATOS
 Numero     : 10
 Alias      : "aaaaa"
 urlConsumo : "www.aaaaaaaaaaaaa"
 Consumos
  Tipo      : "abc"
  SubTtipo  : "aaa"
  ...
DATOS
 Numero     : 10
 Alias      : "aaaaa"
 urlConsumo : "www.aaaaaaaaaaaaa"
 Consumos
  Tipo      : "abc"
  SubTtipo  : "aaa"
  ...

回答1:


Implement a ToString() method for the Consumo class and then implement a ToString() method for the Datos class using the ToString() method for the Consumo class.




回答2:


You must override a "ToString" dafault function like:

public class Consumo 
{
    public string Tipo;
    public string Subtipo;
    public string Concepto;
    public string Cantidad;
    public string Importe;
    public string Total;

   public override string ToString()
   {
   return Tipo + " \n " + Subtipo + " \n "... etc;
   }
}

refer to the escape sequences section in C# development guide... http://msdn.microsoft.com/en-us/library/h21280bw.aspx or http://msdn.microsoft.com/en-us/netframework/aa569608




回答3:


When string representations are used for visualization and similar purposes, the best approach is to override ToString method. Start with the most nested type, and go up the hierarchy. Use ToString of nested objects to implement ToString of outer objects. One very useful method in formatting collections of objects is string.Join(): it lets you format a collection without an explicit loop.



来源:https://stackoverflow.com/questions/8693485/c-sharp-object-to-string-to-display-it-in-text-format

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!