mercredi 22 février 2017

Traverse an object using GetProperties

I would like to see all properties on an object and i would like to see an object printed out. Something like perls Data::Dumper or php's var_dump.

I have tried my own code but finally tried this that i found online. But every code fails on StackOverFlowException caused by an object having a reference to itself.

In the example below i am trying to print out the object CurrentThread but that is a class of type Thread which has a property called CurrentThread which points to the same object and i am stuck in an endless loop.

Is there a method already in .Net that i don't know about or how sould i try to solve this. I am thinking that maybe an object/class could have a child which has a parent property also causing an endless loop.

Since there are methods for dumping an object in other languages this is of course not the first time this probles has been detected.

How can this be solved?

I want all data to be printed out, not just (as an example):

obj.arr = string[]

i would need:

obj.arr = ["a", "b"]

Does anyone have any good input for me?

   var sb = new StringBuilder();
   PrintProperties(System.Threading.Thread.CurrentThread, 0, sb);

    public void PrintProperties(object obj, int indent, StringBuilder sb)
    {
        if (obj == null) return;
        string indentString = new string(' ', indent);
        Type objType = obj.GetType();
        PropertyInfo[] properties = objType.GetProperties();
        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, sb);
                }
            }
            else
            {
                // This will not cut-off System.Collections because of the first check
                if (property.PropertyType.Assembly == objType.Assembly)
                {
                    //Console.WriteLine("{0}{1}:", indentString, property.Name);
                    sb.AppendLine(string.Format("{0}{1}:", indentString, property.Name));

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





Aucun commentaire:

Enregistrer un commentaire