对列表和打印值的反射

本文关键字:反射 打印 列表 | 更新日期: 2023-09-27 18:02:39

我编写了一个方法,它接受一个泛型参数,然后输出它的属性。我用它来测试我的web服务。它正在工作,但我想添加一些我不知道如何实现的功能。我想打印列表的值,因为现在它只写system。collection。generic。

以下是我到目前为止的代码,它适用于基本类型(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());
}

对列表和打印值的反射

你可以这样做:

    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并打印出单个值(我每行打印一个,但显然,您可以做不同的操作)

列表中的元素可以通过索引器属性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 });

我通常在每个项目之间打印一个,

为方便起见,我创建了一个简单的扩展方法:

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

调用myList.StringJoin()方法

您当然可以修改该方法,以便在每次直接调用string.Join时使用另一个分隔符。

下面是一个代码片段,假设您的List是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());
                }

我想你需要这样的东西:

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>方法。

现在,请记住,您的原始TTItemType不一定相同。当您使用反射调用FormatList时,您希望将TPlaceholder绑定到TItemType。完成这些后,只需调用格式化方法并将列表的实际实例传递给它,该实例将返回一个字符串。然后你可以输出这个字符串。

希望对你有帮助。

借鉴上面的例子,这里是我的完整解决方案。这已经经过测试,并通过打印每个元素的属性来处理传入的IEnumerable。它不是递归的,但很容易添加。

请注意,上面的许多示例在使用索引属性(例如列表)时会崩溃。property.GetValue()中参数计数不匹配。

在这里通过使用LINQ的这一点来过滤具有索引属性的属性来避免它。

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

下面的扩展方法的完整示例。

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