我有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的列表?
答案 0 :(得分:5)
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);
答案 1 :(得分: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);
}