列表和打印值的反射

gor*_*i93 6 c# reflection

我写了一个接受泛型参数然后打印其属性的方法.我用它来测试我的网络服务.它正在工作,但我想添加一些我不知道如何实现的功能.我想打印列表的值,因为它现在只写了预期的System.Collection.Generic.List1.

这是我到目前为止的代码,这适用于基本类型(int,double等):

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());
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*ope 7

你可以这样做:

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


    }
Run Code Online (Sandbox Code Playgroud)

然后,它会通过任何的IEnumerable枚举并打印出各个值(我将它们打印每行一个,但很明显,你可以做不同的.)