2

Preciso escrever todas as propriedades primitivas de um objeto C# independente de quantos "níveis" eu entre nesses objetos.

Eu tenho o seguinte objeto em Javascript:

var objeto = {
  propriedade:{
    valor:42
  },
  atributo:"foo"  
}

Então para acessar todas as propriedades dele recursivamente, faço o seguinte:

function PrintAllProperties(obj){
      for(var prop in obj){
          if(typeof obj[prop]==="object")
             PrintAllProperties(obj[prop]);
          else
             console.log(obj[prop]);
         }
} PrintAllProperties(objeto);

Com isso a saída é formada por todas as propriedades com valor primitivo não importando a quantidade de níveis que tiveram de ser acessados daquele objeto "pai" ( exemplo funcionando )

Como fazer isso em C#?

1 Resposta 1

4

Seria algo assim:

public void PrintProperties(object obj, int indent)
{    
    if (obj == null) return;
    string indentString = new string(' ', indent);
    Type objType = obj.GetType();
    PropertyInfo[] properties = objType.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
    foreach (PropertyInfo property in properties)
    {
        object propValue = property.GetValue(obj, null);
        var elems = propValue as IList;
        if (elems != null)
        {
            foreach (var item in elems)
            {
                PrintProperties(item, indent + 3);
            }
        }
        else
        {
            if (property.PropertyType.Assembly == objType.Assembly)
            {
                Console.WriteLine("{0}{1}:", indentString, property.Name);

                PrintProperties(propValue, indent + 2);
            }
            else
            {
                Console.WriteLine("{0}{1}: {2}", indentString, property.Name, propValue);
            }
        }
    }
}

Tirei daqui, com algumas modificações. Isto imprime as propriedades, indentando em console.

2
  • Nota que isso só vai listar as propriedades públicas.
    – dcastro
    9/09/2015 às 23:02
  • @dcastro Coloquei com todas as BindingFlags. Espero não ter esquecido de nada. Obrigado! 9/09/2015 às 23:16

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .