Reflection of list and print values

I wrote a method that takes a generic parameter and then prints its properties. I use it to check my web service. It works, but I want to add some functions that I don’t know how to implement. I want to print the values ​​of the lists, because now it just writes System.Collection.Generic.List1, which is expected.

Here is my code so far, it works for base types (int, double, etc.):

static void printReturnedProperties<T>(T Object)
{ 
   PropertyInfo[] propertyInfos = null;
   propertyInfos = Object.GetType().GetProperties();

   foreach (var item in propertyInfos)
      Console.WriteLine(item.Name + ": " + item.GetValue(Object).ToString());
}
+5
source share
6 answers

You can do something like this:

    static void printReturnedProperties(Object o)
    {
        PropertyInfo[] propertyInfos = null;
        propertyInfos = o.GetType().GetProperties();



        foreach (var item in propertyInfos)
        {
            var prop = item.GetValue(o);

            if(prop == null)
            {
                Console.WriteLine(item.Name + ": NULL");
            }
            else
            {
                Console.WriteLine(item.Name + ": " + prop.ToString());
            }


            if (prop is IEnumerable)
            {
                foreach (var listitem in prop as IEnumerable)
                {
                    Console.WriteLine("Item: " + listitem.ToString());
                }
            }
        }


    }

It will then list through any IEnumerable and print individual values ​​(I print them one at a time, but obviously you can do different ones.)

+5
source

indexer Item. ( PropertyInfo.GetValue, object, MethodInfo.Invoke), .

int index = /* the index you want to get here */;
PropertyInfo indexer = Object.GetProperty("Item");
object item = indexer.GetValue(Object, new object[] { index });
+3

, .

, :

public static class ListEx
{
    public static string StringJoin<T>(this IEnumerable<T> items)
    {
        return string.Join(", ", items);
    }
}

myList.StringJoin().

, , , och call string.Join.

+2

, , T.

 foreach (PropertyInfo item in propertyInfos)
            {
                Object obj = item.GetValue(object,null);
                if (!obj.GetType().IsValueType)
                {
                    if (obj.GetType() == typeof(String))
                    {
                        Console.WriteLine(obj.ToString());
                    }
                    else if (obj.GetType() == typeof(List<T>))
                    {
                        //run a loop and print the list

                    }
                    else if (obj.GetType().IsArray) // this means its Array
                    {
                        //run a loop to print the array
                    }

                }
                else
                {
                    //its primitive so we will convert to string 
                    Console.WriteLine(obj.ToString());

                }
+1

, - :

public class Program
{
    public static void PrintProperties<T>(T t)
    {
        var properties = t.GetType().GetProperties();

        foreach (var property in properties)
        {
            var name = property.Name;
            var value = property.GetValue(t, null);

            if (property.PropertyType.IsGenericType && property.PropertyType == typeof(IEnumerable<>))
            {
                var formatList = typeof(Program).GetMethod("FormatList", new[] { value.GetType() });

                // value.GetType().GetGenericArguments().First() will get you the underlying type of the list,
                // i.e., the TItemType where the property you are currently
                // handling is of type IEnumerable<TItemType>
                formatList.MakeGenericMethod(value.GetType().GetGenericArguments().First());

                value = formatList.Invoke(null, new object[] { value });

                Console.Out.WriteLine(name + ": " + value);
            }
            else
            {
                Console.Out.WriteLine(name + ": " + value);
            }
        }
    }

    public static string FormatList<TPlaceholder>(IEnumerable<TPlaceholder> l)
    {
        return string.Join(", ", l);
    }
}

, - , , - IEnumerable<TItemType>, FormatList<TPlaceholder>.

, T TItemType . FormatList , TPlaceholder TItemType. , , . .

, .

+1

, . IEnumerable, . , .

Keep in mind that many of the examples above will crash with indexed properties (like lists). Parameter counter mismatch in property.GetValue () .

This avoids filtering properties that indexed properties using this LINQ bit.

Where(x=>!x.GetIndexParameters().Any())

A full example in the form of an extension method is below.

    /// <summary>
    /// Returns string representation of object property states i.e. Name: Jim, Age: 43
    /// </summary>
    public static string GetPropertyStateList(this object obj)
    {
        if (obj == null) return "Object null";

        var sb = new StringBuilder();
        var enumerable = obj as IEnumerable;

        if (enumerable != null)
        {
            foreach (var listitem in enumerable)
            {
                sb.AppendLine();
                sb.Append(ReadProperties(listitem));
            }
        }
        else
        {
            sb.Append(ReadProperties(obj));
        }

        return sb.ToString();
    }

    private static string ReadProperties(object obj)
    {
        var sb = new StringBuilder();
        var propertyInfos = obj.GetType().GetProperties().OrderBy(x => x.Name).Where(x=>!x.GetIndexParameters().Any());

        foreach (var prop in propertyInfos)
        {
            var value = prop.GetValue(obj, null) ?? "(null)";
            sb.AppendLine(prop.Name + ": " + value);
        }

        return sb.ToString();
    }
0
source

All Articles