通用方法接受List<T>

4
我有5个类,分别代表数据网格的一行。所有这些类都继承自CoreGrid的抽象类。
我有一个导出机制,它使用反射来确定要导出的列。目前,我为每种类型的网格(ExportOrganisations、ExportPeople、ExportEvents)编写了一个方法,但这很糟糕,因为它们之间唯一不同的是查找类型的部分。下面是示例代码:
public string ExportEvents(List<EventGrid> events)
{
    DataTable report = new DataTable();

    EventGrid ev = new EventGrid();

    Type t = ev.GetType();

    PropertyInfo[] props = t.GetProperties();

    foreach (PropertyInfo prop in props)
    {
        if (!prop.Name.Contains("ID"))
        {
            report.Columns.Add(prop.Name);
        }
    }

    foreach (var item in events)
    {
        DataRow dr = report.NewRow();

        Type itemType = item.GetType();

        PropertyInfo[] itemProps = itemType.GetProperties();

        foreach (PropertyInfo prop in itemProps)
        {
            if (report.Columns.Contains(prop.Name))
            {
                if (prop.GetValue(item, null) != null)
                {
                    dr[prop.Name] = prop.GetValue(item, null).ToString().Replace(",", string.Empty);
                }
            }
        }

        report.Rows.Add(dr);
    }

    return GenerateCSVExport(report, ExportType.Events);
}

我的问题是,我该如何将这些方法压缩成一个方法,让该方法接受一个从CoreGrid继承的列表?

我想在我的答案中添加一些提示:PropertyInfo.GetValue和Type.GetProperties是昂贵的调用,尽量将它们减少到最低限度。如果列表中的项目都是相同类型的,请使用props而不是itemprops来提高性能。 - Bas
2个回答

6
public string ExportEvents<T>(List<T> events) where T : CoreGrid
{
    DataTable report = new DataTable();

    Type t = typeof(T);

    //your magic here
}

然后使用

var result = ExportEvents<EventGrid>(eventList);

哇,考虑到我在发布这个令人尴尬的简单问题之前花了大约2个小时进行研究! - Paul
我还将对泛型类型添加约束: public string ExportEvents<T>(List<T> events) where T : CoreGrid - munissor

3
应该是这样的。由于可以推断类型,您不必更改当前的调用签名,只需将所有内容指向通用方法:
//if myList is a list of CoreGrid or derived.
string export = ExportEvents(myList);


public string ExportEvents<T>(List<T> events) where T : CoreGrid
{
    DataTable report = new DataTable();

    Type t = typeof(T);

    PropertyInfo[] props = t.GetProperties();

    foreach (PropertyInfo prop in props)
    {
        if (!prop.Name.Contains("ID"))
        {
            report.Columns.Add(prop.Name);
        }
    }

    foreach (var item in events)
    {
        DataRow dr = report.NewRow();

        Type itemType = item.GetType();

        PropertyInfo[] itemProps = itemType.GetProperties();

        foreach (PropertyInfo prop in itemProps)
        {
            if (report.Columns.Contains(prop.Name))
            {
        var propValue = prop.GetValue(item, null)
                if (propValue != null)
                {
                    dr[prop.Name] = propValue.ToString().Replace(",", string.Empty);
                }
            }
        }

        report.Rows.Add(dr);
    }

    return GenerateCSVExport(report, ExportType.Events);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接