接受List的泛型方法
本文关键字:泛型方法 List 接受 | 更新日期: 2023-09-27 18:16:22
我有5个类,它们代表数据网格的一行。所有这些类都继承自CoreGrid的抽象类。
我有一个导出机制,它使用反射来找出要导出的列。目前,我对每种类型的网格(exportorganizations, 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继承的列表?
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);
应该是这样的。由于能够推断类型,您不必更改当前调用签名,只需将所有内容指向泛型方法:
//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);
}