c# object to string to display it in text format

2019-07-15 07:25发布

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"
  ...

标签: c# object render
3条回答
闹够了就滚
2楼-- · 2019-07-15 08:06

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.

查看更多
闹够了就滚
3楼-- · 2019-07-15 08:08

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

查看更多
Juvenile、少年°
4楼-- · 2019-07-15 08:11

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.

查看更多
登录 后发表回答