是否有通用的方法来迭代和打印未知集合中的值? [英] Is there a generic method to iterate and print a values in an unknown collection?

查看:57
本文介绍了是否有通用的方法来迭代和打印未知集合中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个这样的Print方法:

Let's say, I have a Print method like this:

private static void Print(IEnumerable items)
{
    // Print logic here
}

我想将一个集合类传递给此Print方法,该方法应该像表一样打印所有字段.例如,我的输入集合可以是人",订单"或汽车"等.

I want to pass a collection class to this Print method, which should print all the fields like a table. For example, my input collection can be "Persons" or "Orders" or "Cars" etc.

如果我将汽车"集合传递给Print方法,它将打印汽车"详细信息列表,例如:制造,颜色,价格,类别等.

If I pass the "Cars" collection to the Print method, it should print the list of "Car" details such as: Make, Color, Price, Class etc.

直到运行时,我才知道集合的类型.我尝试并使用TypeDescriptorsPropertyDescriptorCollection实现了解决方案.但是,我认为这不是一个好的解决方案.还有其他使用表达式或泛型实现此目的的方法吗?

I won't know the type of the collection until run-time. I tried and achieved a solution using TypeDescriptors and PropertyDescriptorCollection. But, I don't feel that is a good solution. Is there any other way to achieve this using expressions or generics?

推荐答案

您可以这样实现Print:

You could implement Print like this:

static void Print<T>(IEnumerable<T> items)
{
    var props = typeof(T).GetProperties();

    foreach (var prop in props)
    {
        Console.Write("{0}\t", prop.Name);
    }
    Console.WriteLine();

    foreach (var item in items)
    { 
        foreach (var prop in props)
        {
            Console.Write("{0}\t", prop.GetValue(item, null));
        }
        Console.WriteLine();
    }
}

它只是循环遍历类的每个属性以打印属性的名称,然后在每个项目上打印,并为每个项目打印属性的值.

It simply loops over each property of the class to print the name of the property, then prints over each item and for each item it prints the values of the properties.

我认为您应该在此处使用泛型(与其他答案中的建议相反);您希望集合中的项目为单一类型,以便可以打印表格标题.

I would argue that you should use generics here (as opposed to suggestions in other answers); you want the items in the collection to be of a single type so that you can print table headers.

对于表格格式,您可以查看

For table formatting you can check the answers to this question.

这篇关于是否有通用的方法来迭代和打印未知集合中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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