反映在列表和打印值上 [英] reflection on List and printing values

查看:41
本文介绍了反映在列表和打印值上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I wrote a method that accepts a generic parameter and then it prints its properties. I use it to test my web service. It's working but I want to add some features that I don't know how to implement. I want to print values of lists, because now it just writes System.Collection.Generic.List1 which is expected.

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

Here is my code so far, this is working for basic 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());
}

推荐答案

您可以执行以下操作:

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


    }

然后它将枚举任何IEnumerable并打印出各个值(我正在每行打印一个,但是显然,您可以做不同的事情.)

It will then enumerate through any IEnumerable and print out the individual values (I'm printing them one per line, but obviously, you can do different.)

这篇关于反映在列表和打印值上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆