List all properties of a C # object?

2

I need to write all the primitive properties of a C # object regardless of how many "levels" I enter into those objects.

I have the following object in Javascript:

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

Then to access all properties of it recursively, I do the following:

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

This output is formed by all properties with primitive value regardless of the amount of levels that had to be accessed from that "parent" object ( example working )

How to do this in C #?

    
asked by anonymous 09.09.2015 / 23:02

1 answer

3

It would look something like this:

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

I removed it , with some modifications. This prints the properties, indenting in console.

    
09.09.2015 / 23:03